【问题标题】:How to read two strings separated by ":" in c如何在c中读取由“:”分隔的两个字符串
【发布时间】:2013-02-15 05:22:49
【问题描述】:

我需要知道如何读取字符串并将其分成两部分,如下例所示。

我在文件@amanda:@bruna 中有这个字符串,但我无法读取为单独的单词,并且每个单词都存储在两个不同的变量中,如下所示:

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

你能帮帮我吗?

【问题讨论】:

标签: c string file scanf


【解决方案1】:

使用扫描集来防止第一个 %s 消耗整行,因为 %s 只会在遇到空格时停止消耗:

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

%19[^:] 表示最多读取 19 个字符,但遇到冒号时停止。指定宽度可防止缓冲区溢出。始终检查 scanf() 的结果,它返回所做的赋值数,以确保后续代码不会处理陈旧或未初始化的变量。

【讨论】:

  • 谢谢,你帮了我很多
  • @user1769712,完全没问题。我也在 stackoverflow 上了解了扫描集,非常有用(扫描集和 SO!)。
【解决方案2】:
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);

【讨论】:

    【解决方案3】:

    没有必要使用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';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-01
      • 2018-05-06
      • 1970-01-01
      • 2016-07-15
      • 2014-01-05
      • 1970-01-01
      相关资源
      最近更新 更多