-1

I've been working on a problem. I need to scan for a \n to end the cycle and delete it to not remain in a variable with other text. So far I have this:

do {                                    
    scanf("%[^\n]", userinput);            //loads stdin to char[] variable  
    end = userinput[0];                    //loads one char to char variable
    scanf("%*c");                          //should remove \n
    strcpy(inputstorage[i], userinput);    //copies userinput into 2d array of 
    i++;                                   //string with \n removed
} while (end != '\n');                     //should end cycle when I hit enter

What this does is, when I press enter it keeps the last char in the variable end.

For example I enter: 'Hello'

In userinput is: 'Hello'

In end is 'H'

When I hit enter afterwards the end variable should contain \n but it contains 'H' for some reason. I appreciate all the help you can provide

D.P
  • 17
  • 3

2 Answers2

2

You can use use scanf, getline or fgets to get the line and then strcspn to remove the "\n".

eg. userInfo[strcspn(userInfo, "\n")] = 0;

Alex G
  • 1,897
  • 2
  • 10
  • 15
2

end = userinput[0]; saves the first character of input. scanf("%[^\n]", userinput); does not put a '\n' in userinput[], so testing if end is an end-of-line is not useful.


Use fgets() to read a line

char userinput[100];
if (fgets(userinput, sizeof userinput, stdin)) {

Then lop off the potential '\n' via various means.

 size_t len = strlen(userinput);
 if (len > 0 && userinput[len-1] == '\n') userinput[--len] = '\0';

If code is obliged to use scanf(),

int count;
do {        
  char userinput[100];

  // Use a width limiter and record its conversion count : 1, 0, EOF
  // scanf("%[^\n]", userinput);
  count = scanf("%99[^\n]", userinput);

  // Consume the next character only if it is `'\n'`. 
  // scanf("%*c");
  scanf("%*1[\n]");

  // Only save data if a non-empty line was read
  if (count == 1) {
    strcpy(inputstorage[i], userinput);
    i++;
  } 
} while (count == 1);
// Input that begins with '\n' will have count == 0

A re-formed loop could use

char userinput[100];
int count;
while ((count = scanf("%99[^\n]", userinput)) == 1) {
  scanf("%*1[\n]");
  strcpy(inputstorage[i++], userinput);
}
scanf("%*1[\n]");

Note OP's code use '/n' in while (end != '/n');. This is not the end of line character '\n' but a rarely used multi-character constant. Certainly not what OP wanted. It also implied that warnings were not fully enabled. Save time enable all warnings. @aschepler.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256