Andrew530
Andrew530

Reputation: 13

How to read a string until new line except for the first char is newline itself in C?

void Init() {
    fflush(stdin);
    printf("Input the cup name:");

    scanf("%[^\n]s", array_of_water[indexx].name); 
    array_of_water[indexx].water = rand() % 31 + 20;
}

"%[^\n]s" I know it will read the string until it encounters newline. But, How to make exception for the first char to be not newline.

If I press enter on my keyboard the string will save \n as its element. But I don't want that, I want to let user enter except for newline itself. Besides that, how the format specifiers change if I want read until encounter alphabet/number/other symbols?

Upvotes: 0

Views: 89

Answers (1)

chux
chux

Reputation: 154280

How to read a string until new line except for the first char is newline itself ...?

Correct use of scanf() will succeed

OP's scanf("%[^\n]s", array_of_water[indexx].name); lacks context as the size of array_of_water[indexx].name is unknown, as well as the input. fflush(stdin); is also undefined behavior. Delete it.

The s in "%[^\n]s" is amiss.

Drop the s.

char buf[100];
int count = scanf("%99[^\n]", buf);
switch (count) {
  case EOF: puts("End of file or input error"); break;
  case   1: printf("Success <%s>\n", buf); break;
  case   0: puts("Nothing read"); break;
}

Left to do:

  • Consume rest of non-'\n' line if length of buf was 99.

  • Consume final '\n'.

  • Handle pesky null characters, if they were read.


Easier to just use fgets().

char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
  buf[strcspn(buf, "\n")] = 0; // Lop off potential \n
  printf("Success <%s>\n", buf);
} else {
  case EOF: puts("End of file or input error"); break;
}

Left to do:

  • Maybe consume rest of non-'\n' line if length of buf read was 99.

Upvotes: 2

Related Questions