2011-10-01 194 views
0

我想从输入字符串中排序整数和字符串。从C++中的输入字符串中分隔字符串和int字符串

#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

我明白任何帮助。

回答

2

如果您想使用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); 
} 

测试: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

0

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

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

难道你不能只用一个scanf来完成吗?

scanf("%d%s", &y, z); 
+0

我觉得应该是'atoi'而不是'itoa' – phoxis

+0

@phoxis:你说得对,我让他们倒退。谢谢,修复。 –