【问题标题】:How to read multiword string from stdin in Objective-C?如何在 Objective-C 中从标准输入读取多字字符串?
【发布时间】:2019-09-17 02:44:06
【问题描述】:

试图解决一个需要从标准输入读取输入的问题。如果单词之间没有任何空格,我可以使用代码读取标准输入:

输入:

M
Blue 
Balae

代码:

NSString *word;
char word_temp[50];
while ( scanf("%s",word_temp) >= 1){   
    word = [NSString stringWithFormat:@"%s", word_temp];
    printf("%s \n",[word UTF8String]);
}

输出(如预期):

M 
Blue 
Balae 

如果输入的单词有空格,上面的代码会将空格后面的单词打印到下一行,因为scanf会将字符读入缓冲区,直到遇到空格或换行符。为了解决这个问题,我改变了scanf的格式说明符这样它就应该读入缓冲区,直到遇到换行符为止。

输入:

M
Blue Whale
Balae

代码:

NSString *word;
char word_temp[50];
while ( scanf("%[^\n]s]",word_temp) >= 1){       
      word = [NSString stringWithFormat:@"%s", word_temp];
      printf("%s \n",[word UTF8String]);
 }

预期输出:

M
Blue Whale
Balae

实际输出:

// ~ no response on stdout ~

如何读取包含多个单词和空格的行并将其转换为 NSString 对象?

【问题讨论】:

    标签: objective-c scanf stdin


    【解决方案1】:

    scanf() 不接受正则表达式作为输入模式。

    如果要获取单行输入作为字符串,可以使用C函数getline()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2014-03-20
      • 1970-01-01
      • 2012-10-08
      相关资源
      最近更新 更多