c++中从输入字符串中分离字符串和整型
separating string of characters and int from a input string in 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存储在一个单独的字符变量中。
输入:123他们输出:x = 123,某些char变量= abc1
谢谢你的帮助。
如果您希望使用C编程语言的概念,那么考虑使用strtol
而不是atoi
。它会告诉你它停在哪个字符处:
另外,永远不要在scanf
中使用%s
,始终指定缓冲区大小(- 1,因为%s在存储输入后会添加' ')
#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: %dnremainder of the string: %sn",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
如果这是您想要的方式,那么在提取数字后将其转换回其文本表示形式,该字符串长度将告诉您在哪里找到字符串的开头。所以对于你的特定例子:
char* x = "123abc1"
atoi( x ) -> 123;
itoa/sprintf( 123 ) -> "123", length 3
x + 3 -> "abc1"
你就不能用一次扫描吗?
scanf( "%d%s", &y, z );
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 提升不良词法强制转换:将字符串转换为无符号长整型时,无法将源类型值解释为目标
- 将字符串中以十六进制形式存储的负长整型值转换为 C++ 中的长整型变量
- 如何以优雅高效的方式将无符号/有符号整数/长整型转换为 C 字符串?
- 如何在 c++ 中将十六进制字符串转换为长整型字符串
- 将字符串转换为长整型
- 将字符串存储在无符号长整型的向量中
- 整型到字符串:不使用stoi库
- 将十六进制二进制或十进制字符串转换为长整型字符串C++
- c++中的字符串和整型
- c++中字符串到整型的哈希函数
- 使用整型变量检查用户输入是整型还是字符串
- 将数字字符串转换为整型,然后再转换为数组
- 从文件中抓取值以查看它们是整型还是字符串
- 将字符串转换为整型数组
- 如何正确输入整型,整型的向量,整型和字符串的向量
- 将字符串映射到整型CPP -输出在执行期间挂起
- 在c++中从文件中读取字符串、整型和双精度的混合
- 制作一个将字符串转换为整型和字符的计算器
- c++:字符串+整型路径