0

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

#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

我很感激任何帮助。

4

2 回答 2

2

如果您希望使用 C 编程语言概念,请考虑使用strtolintead of atoi. 它会让你知道它停在了哪个角色:

此外,永远不要%s在 a 中使用scanf,始终指定缓冲区大小(减一,因为 %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

于 2011-10-01T05:29:08.347 回答
0

如果这是您想要的方式,那么在提取数字后将其转换回其文本表示形式,字符串长度将告诉您要找到字符串的开头。因此,对于您的特定示例:

char* x = "123abc1"
atoi( x ) -> 123;
itoa/sprintf( 123 ) -> "123", length 3
x + 3 -> "abc1"

你不能只用一个scanf来做吗?

scanf( "%d%s", &y, z );
于 2011-10-01T04:49:23.057 回答