c++ - 在c++中将字符串和int与输入字符串分开

标签 c++ string atoi

我正在尝试对输入字符串中的整数和字符串进行排序。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

int main(){
    char x[10];
    int y;
    printf("string: ");
    scanf("%s",x);
    y=atoi(x);
    printf("\n %d", y);
    getchar();
    getchar(); }

假设输入是123abc1 使用 atoi 我可以从输入字符串中提取 123,我现在的问题是如何提取 abc1?

我想将 abc1 存储在一个单独的字符变量上。

输入:123abc1 输出:x = 123,一些字符变量 = abc1

感谢任何帮助。

最佳答案

如果您希望使用 C 编程语言概念,请考虑使用 strtol 而不是 atoi。它会让您知道它停在了哪个字符处:

此外,切勿在 scanf 中使用 %s,始终指定缓冲区大小(减一,因为 %s 会在存储您的输入后添加一个“\0” )

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    printf("string: ");
    char x[10];
    scanf("%9s",x);
    char *s;
    int y = strtol(x, &s, 10);
    printf("String parsed as:\ninteger: %d\nremainder of the string: %s\n",y, s);
}

测试:https://ideone.com/uCop8

在 C++ 中,如果该标记没有错误,则有更简单的方法,例如流 I/O。

例如,

#include <iostream>
#include <string>
int main()
{
    std::cout << "string: ";
    int x;
    std::string s;
    std::cin >> x >> s;
    std::cout << "String parsed as:\ninteger: " << x << '\n'
              << "remainder of the string: " << s << '\n';
}

测试:https://ideone.com/dWYPx

关于c++ - 在c++中将字符串和int与输入字符串分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7618235/

相关文章:

c - 在 C 中使用 atoi() 时出现运行时错误

c++ - 在 VS2013 中构建 boost 库

c++ - 我可以从 MSVC 编译的 exe 文件中删除 *.exe.manifest 文件吗?

c++ - 从具有任意结构的C++中的字符串中提取整数

C 字符值算术

python - 如何将位串转换为 utf-8 字符串?

c++ - C++ 中的霍夫曼编码文件

c++ - 在 ios 编程中包括 c++ 库

c - 返回指向字符串的指针数组

c# - 如何在 DataGridView 中格式化带有最大值和最小值的小数列?