将字符串和 int 与 c++ 中的输入字符串分开
我正在尝试对输入字符串中的整数和字符串进行排序。
#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,一些 char 变量 = abc1
我感谢任何帮助。
I am trying to sort integers and strings from an input string.
#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(); }
suppose the input is 123abc1
using atoi i could extract 123 from the input string, my question now is how do i extract abc1?
I want to store abc1 on a separate character variable.
input: 123abc1
output: x = 123, some char variable = abc1
I appreciate any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您希望使用 C 编程语言概念,请考虑使用
strtol
而不是atoi
。它会让您知道它停在哪个字符处:此外,切勿在
scanf
中使用%s
,始终指定缓冲区大小(减一,因为 %s 会添加存储输入后的 '\0')测试: https://ideone.com/uCop8
在 C++ 中,如果该标签没有错误,还有更简单的方法,例如流 I/O。
例如,
测试:https://ideone.com/dWYPx
If you wish to use the C programming language concepts, then consider using
strtol
intead ofatoi
. It will let you know what character did it stop at:Also, never use
%s
in ascanf
, always specify the buffer size (minus one, since %s will add a '\0' after storing your input)test: https://ideone.com/uCop8
In C++, if that tag was not a mistake, there are simpler approaches, such as stream I/O.
For example,
test: https://ideone.com/dWYPx
如果这是您想要的方式,那么在提取数字后将其转换回其文本表示形式,并且该字符串长度将告诉您要找到字符串的开头。因此,对于您的特定示例:
您不能只用一个 scanf 来完成它吗?
If that's the way you want to go, then after extracting the number convert it back to its textual representation and that string length will tell you were to find the start of the string. So for your particular example:
Can't you just do it with a single scanf?