Why does my code keep printing twice? I don't understand the problem [duplicate]

那年仲夏 提交于 2021-01-28 21:13:13

问题


#include <stdio.h>

#define MAX_STRING_LENGTH 1024

int main(){ 

char input_name_string[MAX_STRING_LENGTH+1],motive_string[MAX_STRING_LENGTH+1];
printf("What is your name?\n");
scanf("%1024s",input_name_string);
printf("your name is %s \n", input_name_string);
printf("What is your motive?\n");
scanf(" %1024s",motive_string);
printf("your motive is %s \n", motive_string);
return 0; }

So I wrote this simple program for a project in school to try and learn how scanf and printf work. For some reason when this runs it prints the first word in each string on one line then the second word on another line. I don't understand why this is happening? I don't have experience in C but the logic in my code seems correct? Any suggestions


回答1:


The function scanf with the conversion format specifier used by you reads characters until a white space character is encountered.

Instead use the function fgets.

For example

fgets( input_name_string, sizeof( input_name_string ), stdin );

The function can append also the new line character to the entered string. To remove it you can write

#include <string.h>

/ …

input_name_string[ strcspn( input_name_string, "\n" ) ] = '\0';

As for you format specifier

scanf("%1024s",input_name_string); 

than in any case it is incorrect. Instead of 1024 as the field width should be one less than the size of the character array to reserve one character for the terminating zero character '\0'.

You could write

scanf( "%1023[^\n]\n", input_name_string );


来源:https://stackoverflow.com/questions/59883621/why-does-my-code-keep-printing-twice-i-dont-understand-the-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!