为什么我的代码不断打印两次?我不明白这个问题 [英] Why does my code keep printing twice? I don't understand the problem

查看:65
本文介绍了为什么我的代码不断打印两次?我不明白这个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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; }

所以我为学校的一个项目编写了这个简单的程序,试图了解 scanf 和 printf 的工作原理.出于某种原因,当它运行时,它会在一行上打印每个字符串中的第一个单词,然后在另一行上打印第二个单词.我不明白为什么会这样?我没有 C 方面的经验,但我的代码中的逻辑似乎是正确的?任何建议

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

推荐答案

带有转换格式说明符的函数 scanf 用于读取字符,直到遇到空白字符.

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

改为使用函数 fgets.

例如

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';

至于你的格式说明符

scanf("%1024s",input_name_string); 

在任何情况下都是不正确的.而不是 1024,因为字段宽度应该比字符数组的大小小 1,以便为终止零字符 '\0' 保留一个字符.

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'.

你可以写

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

这篇关于为什么我的代码不断打印两次?我不明白这个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆