简体   繁体   English

在C中输入带空格的字符串

[英]Inputting a string with spaces in C

I want my program to prompt the user for how many sentences they want to write and then enter those sentences. 我希望程序提示用户要写​​多少个句子,然后输入这些句子。 However, when I try entering the sentences, I keep getting errors. 但是,当我尝试输入句子时,会不断出现错误。 I tried using several different fucntions but all of them gave some kind of error. 我尝试使用几种不同的功能,但所有功能都产生了某种错误。 For example, right now I am trying to use fgets() and after I enter the first sentence it gives me a segmentation fault. 例如,现在我正在尝试使用fgets(),在输入第一句话之后,它给我带来了句段错误。 Can someone tell me what is the best way to take input for a string with spaces and how to fix my problem? 有人可以告诉我什么是用空格输入字符串的最佳方法以及如何解决我的问题吗?

int n;
char str[n][80];

printf("Enter number of lines: ");
scanf("%d", &n);

printf("Enter a sentecne: ");
for(int i = 0; i < n; i++){
    fgets(str[i], 80, stdin);
    printf("%s", str[i]);
}

You define the array str before you initialize n . 您可以在初始化n之前定义数组str That means n will have an indeterminate value (which will be seemingly random). 这意味着n将具有不确定的值(看似随机的)。

Move the input of n to before you define str . 定义str 之前n的输入移动到。

you can use read function http://man7.org/linux/man-pages/man2/read.2.html 您可以使用读取功能http://man7.org/linux/man-pages/man2/read.2.html

reading on the file descriptor 0 (standart input), a char *buffer to store your data, and a size_t size to read 读取文件描述符0(标准输入),用于存储数据的char * buffer和要读取的size_t大小

there are several problems in your code 您的代码中有几个问题

int n; // must have a value
int n = 10; // example, here your variable is initialized

you also don't check the return value of scanf 您也不检查scanf的返回值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM