C语言 如何使用 fgets 从输入中获取字符串而不包含换行符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27491005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get a string from input without including a newline using fgets?
提问by countofmontecristo
I'm trying to write an inputted string elsewhere and do not know how to do away with the new line that appears as part of this string that I acquire with stdin and fgets.
我正在尝试在其他地方编写一个输入的字符串,但不知道如何处理作为我使用 stdin 和 fgets 获取的该字符串的一部分出现的新行。
char buffer[100];
memset(buffer, 0, 100);
fgets(buffer, 100, stdin);
printf("buffer is: %s\n stop",buffer);
I tried to limit the amount of data that fgets gets as well as limiting how much of the data is written but the new line remains. How can I simply get the inputted string up to the last character written with nothing else?
我试图限制 fgets 获取的数据量以及限制写入的数据量,但新行仍然存在。我怎样才能简单地将输入的字符串输入到最后一个字符而不写其他字符?
回答by madz
try
尝试
fgets(buffer, 100, stdin);
size_t ln = strlen(buffer)-1;
if (buffer[ln] == '\n')
buffer[ln] = 'size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
buffer[--len] = 'char buffer[100];
// memset(buffer, 0, 100); not needed
if (fgets(buffer, sizeof buffer, stdin) == NULL) { // good to test fgets() result
Handle_EOForIOerror();
}
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
buffer[--len] = '##代码##';
}
printf("buffer is: %s\n stop",buffer);
';
}
';
回答by chux - Reinstate Monica
Simply look for the potential '\n'.
只需寻找潜力'\n'。
After calling fgets(), If '\n'exists, it will be the last charin the string (just before the '\0').
调用后fgets(),如果'\n'存在,它将是char字符串中的最后一个(就在 之前'\0')。
Sample usage
示例用法
##代码##Notes:
笔记:
buffer[strlen(buffer)-1]is dangerous in rare occasions when the first charin bufferis a '\0'(embedded null character).
buffer[strlen(buffer)-1]当第一个char输入buffer是'\0'(嵌入的空字符)时,在极少数情况下是危险的。
scanf("%99[^\n]%*c", buffer);is a problem if the first charis '\n', nothing is read and '\n'remains in stdin.
scanf("%99[^\n]%*c", buffer);如果第一个char是问题'\n',则没有读取任何内容并'\n'保留在stdin.
strlen()is fast as compared to other methods: https://codereview.stackexchange.com/a/67756/29485
strlen()与其他方法相比速度快:https: //codereview.stackexchange.com/a/67756/29485
Or roll your own code like gets_sz
或者滚动你自己的代码 gets_sz

