C语言 从输入字符串在单独的行中打印每个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30304561/
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
Print each word in a separate line from an input string
提问by Rookie_Coder
I'm having trouble printing each word in a separate line from an input string in C. The question from the assignment I'm doing states:
我无法从 C 中的输入字符串在单独的行中打印每个单词。我正在做的作业中的问题指出:
Take a sentence as input and print its words in separate lines.
将一个句子作为输入并将其单词打印在单独的行中。
My Code:
我的代码:
#include<stdio.h>
int main()
{
int i;
char s[100];
scanf("%s", s);
for(i=0; s[i]!=' printf("%s", s[i]);
'; i++)
{
printf("%c", s[i]);
if(s[i]==' ')
{
printf("\n");
}
}
}
Any help would be appreciated.
任何帮助,将不胜感激。
回答by Sourav Ghosh
In your code,
在您的代码中,
printf("%c", s[i]);
is wrong. Change it to
是错的。将其更改为
#include <stdio.h>
#define MAXC 100
int main(void) {
int c = 0;
size_t n = 0;
printf ("\n Enter a sentence.\n\n input: ");
/* read up to 100 characters from stdin, print each word on a line */
while (n < MAXC && (c = getchar ()) != EOF && c != '\n')
{
if (c == ' ')
printf ("\n");
else
printf ("%c", c);
n++;
}
printf ("\n");
if (n == MAXC) /* read and discard remaining chars in stdin */
while ((c = getchar ()) != '\n' && c != EOF);
return 0;
}
as, you're trying to print a charvalue. The conversion specifier for a charis %c.
因为,您正在尝试打印一个char值。a 的转换说明符char是%c。
Note: Always remember, using wrong conversion specifier will lead to undefined behaviour.
注意:永远记住,使用错误的转换说明符会导致未定义的行为。
Also, while scan()-ing with %s, you cannot read the wholespace-delimited input as a singlestring. From the man page,
此外,在使用scan()-ing 时%s,您无法将整个以空格分隔的输入作为单个字符串读取。从手册页,
%s
Matches a sequence of non-white-space characters; the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte (
'\0'), which is added automatically. The input string stops at white space or at the maximum field width, whichever occurs first.
%s
匹配一系列非空白字符;next 指针必须是指向字符数组的指针,该指针的长度足以容纳输入序列和
'\0'自动添加的终止空字节 ( )。输入字符串在空白处或最大字段宽度处停止,以先发生者为准。
You need to use fgets()to do the job.
你需要使用fgets()来完成这项工作。
That said,
那说,
- Indent your code properly, make it human-readable.
- Chnage
scanf("%s", s);toscanf("99%s", s);to avoid possible buffer overflow by putting longer input string than 99chars. - the proper signature for
main()isint main(void).
- 正确缩进您的代码,使其易于阅读。
- Chnage
scanf("%s", s);到scanf("99%s", s);通过投入再输入字符串比99避免可能出现的缓冲区溢出char秒。 - 的正确签名
main()是int main(void)。
回答by David C. Rankin
Rookie, using line-orientedinput like fgetsor getlineis, in general, the proper way to read a line of text. However, when doing simple splitting on a single character, reading a character at a time can be advantageous.
新手,使用面向行的输入,例如fgetsor getline,一般来说,是阅读一行文本的正确方法。但是,在对单个字符进行简单拆分时,一次读取一个字符可能是有利的。
In your case if your task is to read a sentence up to 100 characters and print the words of the sentence out on separate lines, then there is no reason to read the sentence into an array and store the words. You can simply read/print each character until a space is read, then print a newlineinstead of the space. The reading/printing continues until you reach 100 chars, encounter a newlineor EOF:
在您的情况下,如果您的任务是阅读最多 100 个字符的句子并将句子的单词打印在单独的行中,则没有理由将句子读入数组并存储单词。您可以简单地读取/打印每个字符,直到读取一个空格,然后打印一个newline而不是空格。读取/打印继续,直到达到 100 个字符,遇到 anewline或EOF:
$ ./bin/getchar_print_nl_space
Enter a sentence.
input: This is a sentence to split into words.
This
is
a
sentence
to
split
into
words.
Use/Output
使用/输出
char s[MAXC] = {0};
/* read up to 99 characters from stdin into s */
while (n < MAXC - 1 && (c = getchar ()) != EOF && c != '\n')
s[n++] = c;
s[n] = ' for (c = 0; c < n; c++)
if (s[c] == ' ')
printf ("\n");
else
printf ("%c", s[c]);
'; /* null-terminate after last character */
if (n == MAXC - 1) /* read and discard remaining chars in stdin */
while ((c = getchar ()) != '\n' && c != EOF);
Note:if you were going to store all characters, up to 100 (meaning 99 chars and 1 null-terminator), you would need to adjust the length check to n < MAXC - 1and then null-terminate the array:
注意:如果您要存储所有字符,最多 100 个(意味着 99 个字符和 1 个空终止符),您需要将长度检查调整为n < MAXC - 1,然后空终止数组:
/* Program 1_12 */
/* Count number of line, space and char */
/* Replace a char with specific newline */
/* Add blank space in first input */
#include<stdio.h>
int main()
{
int c,nl,nc,ns,nt;
nl=nc=ns=nt=0;
int d,r, prevd, prevr;
printf("Enter which char to replace :: ");
/* prev is stored before of \n */
while((d = getchar()) != '\n' && (prevd = d));
d = prevd;
printf("Enter word below \n");
while((c=getchar()) != EOF)
{
++nc;
if(c==' ')
++ns;
if(c=='\n')
++nl;
if(c=='\t')
++nt;
/* Replace a char with A */
if(c==d)
putchar('\n');
else
putchar(c);
}
printf("total char=%2d, newline=%2d, space=%2d tabs=%2d\n",nc,nl,ns,nt);
return 0;
}
/* Written by: Prakash Katudia <[email protected]> */
You would then repeat the logic checking for a space and printing a newlinein a forloop:
然后,您将重复逻辑检查空格并newline在for循环中打印 a :
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 100
int main() {
char s[100],*c;
int i = 0;
scanf("%[^\n]", s);
//Write your logic to print the tokens of the sentence here.
for ( c = s; *c != (int)NULL; c++){
if ( *c == ' '){
*c = '\n';
}
}
printf("%s",s);
return 0;
}
Understanding both manner of input, character-orientedinput and line-orientedinput will save you time allowing you to match the correct tool to the situation. Here, there is no "more correct" or "less correct" approach, just different ways of doing it.
了解两种输入方式、面向字符的输入和面向行的输入将节省您的时间,让您可以根据情况选择正确的工具。在这里,没有“更正确”或“更不正确”的方法,只是不同的做法。
回答by Prakash Katudia
Below code is the answer. Program also calculates number of space/char and new line.
下面的代码就是答案。程序还计算空格/字符和换行符的数量。
http://cprograming-char-operation.blogspot.com/2018/07/for-given-statement-print-word-in-each.html
http://cprograming-char-operation.blogspot.com/2018/07/for-given-statement-print-word-in-each.html
#include<stdio.h>
#include<string.h>
int main()
{
char a[1000];
int i,len;
scanf("%[^\n]s",a);
len=strlen(a);
for(i=0;i<len;i++)
{
if(a[i] !=' ')
{
printf("%c", a[i]);
}
else
{
printf("\n");
}
}
}
gcc ./my_code.c
gcc ./my_code.c
./a.out
./a.out
Enter which char to replace :: #space#
输入要替换的字符 :: #space#
Enter word below
在下面输入单词
hello how are you hello
你好 你好吗
how
如何
are
是
you
你
回答by NPE
I think one more way to do this work in a better way is as following.
我认为以更好的方式完成这项工作的另一种方法如下。
##代码##
