我正在尝试对输入字符串中的整数和字符串进行排序。
#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);
}
在 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';
}
关于c++ - 在c++中将字符串和int与输入字符串分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7618235/