0
votes

Trying to solve a problem which require reading input from stdin. If the words don't have any white space in between, I am able to read the stdin using the code:

Input:

M
Blue 
Balae

Code:

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

Output(as expected):

M 
Blue 
Balae 

If input words have white space, the above code would print the word after space to next line because scanf will read characters into the buffer until it encounters whitespace or newline character.To solve this problem, I changed the format specifier of scanf so that it should read into the buffer until it encounters a new line character.

Input:

M
Blue Whale
Balae

Code:

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

Expected Output:

M
Blue Whale
Balae

Actual Output:

// ~ no response on stdout ~

How to read a line with multiple words and spaces and convert it to NSString Object?

1

1 Answers

0
votes

scanf() doesn't accept regular expressions as the input pattern.

If you want to get a single line of input as a string, you can use the C function getline().