c++中从输入字符串中分离字符串和整型

separating string of characters and int from a input string in c++

本文关键字:字符串 整型 分离 输入 c++      更新时间:2023-10-16

我正在尝试从输入字符串中排序整数和字符串。

#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 );