首页 > 解决方案 > Newlines being outputted actually as "\n"

问题描述

This is my code so far:

#include<stdio.h>
#include <string.h>

int main(void) {
   char userString[500];
   int x = 0;
   int y = 0;

   while(x < 1 && (!(userString[0] == 'q'))){
      printf("Enter input string:\n");
      fgets(userString,500,stdin);
      for(int i = 0; i < strlen(userString);++i){
         if(userString[i] == ','){
            ++x; 
         }
      }
      if(x < 1){
         printf("Error: No comma in string."); 
         printf("\n");
      }   
   }

This is what is being outputted:

b'Enter input string:\nError: No comma in string.\nEnter input string:\nError: No comma in string.\nEnter input string:\nError: No comma in string.\nEnter input string:

This is the desired output:

Enter input string:
Error: No comma in string.

Enter input string:
Error: No comma in string.

Enter input string:
Error: No comma in string.

Enter input string:

The goal of the program is to get a string with a comma as input, and if there is no comma in the string, to keep prompting the user until they enter "q".I have not even the slightest clue why this could be happening. Would appreciate advice.

标签: cstringwhile-loopnewline

解决方案


推荐阅读