2013-02-28 69 views
1

我需要知道如何读取字符串并将其拆分为两部分,如下例所示。如何读取由c:中的“:”分隔的两个字符串

我有这个字符串的文件@amanda:@bruna,但我不能读成单独的单词,并在两个diferent变量这样每个店:

char userA[20]; 
char userB[20]; 
scanf("%s:%s", userA, userB); 

你能帮助我吗?

+0

http://www.cplusplus.com/reference/cstdio/scanf/'%s'读取任意数量的非空白字符,其中':'绝对不是。 – 2013-02-28 20:52:13

回答

7

使用扫描集,以防止第一%s消耗整条生产线,作为%s只会停止食用,当它遇到的空白:

if (scanf("%19[^:]:%19s", userA, userB) == 2) 
{ 
    /* 'userA' and 'userB' have been successfully assigned. */ 
} 

其中%19[^:]意味着阅读最多19个字符,但停止当遇到冒号。指定宽度预先设置缓冲区溢出。始终检查scanf()的结果,该结果返回分配的数量,以确保后续代码不处理过时的或未初始化的变量。

+0

谢谢,你帮了我很多 – user1769712 2013-02-28 21:01:58

+0

@ user1769712,没问题。我了解了有关stackoverflow的扫描集也非常有用(这两个扫描集和SO!)。 – hmjd 2013-02-28 21:02:56

1
char buf[60]; 
char userA[20]; 
char userB[20]; 
char *ptr; 

scanf("%s", buf); 
ptr = strchr(buf, ':'); 
if (ptr == NULL) 
{ 
    // whatever you want to do if there's no ':' 
} 
*ptr = 0; 
strcpy(userA, buf); 
strpcy(userB, ptr + 1); 
+0

谢谢,我会试试这个方式 – user1769712 2013-02-28 21:04:14

0

有没有必要使用scanf。 (事实上​​,除大学课程外,scanf几乎没有目的)。只读数据:

int main(void) 
{ 
    char line[ 80 ]; 
    char *userA, *userB; 
    fgets(line, sizeof line, stdin); /* Need to check that a full line was read */ 
    userA = line; 
    userB = strchr(line, ':'); /* Need to check that the input contains a colon */ 
    *userB++ = '\0'; 
相关问题