如何在C语言中输入多字字符串
我有这个节目。我想在二维数组中输入多个单词字符串。但该程序不是在二维数组的第一个数组中输入整个字符串,而是在前三个数组中分别输入字符串的前三个字(正如我在二维数组中定义的行数)。节目如下:如何在C语言中输入多字字符串,c,string,multidimensional-array,C,String,Multidimensional Array,我有这个节目。我想在二维数组中输入多个单词字符串。但该程序不是在二维数组的第一个数组中输入整个字符串,而是在前三个数组中分别输入字符串的前三个字(正如我在二维数组中定义的行数)。节目如下: int main() { char title[50]; int track; int question_no; printf("\nHow many questions?\t"); scanf("%d",&question_no); track=0; char question[question_
int main()
{
char title[50];
int track;
int question_no;
printf("\nHow many questions?\t");
scanf("%d",&question_no);
track=0;
char question[question_no][100];
while(track<=question_no)
{
printf("Question no %d is:",track+1);
scanf("%s",question[track]);
printf("Q %d.%s",track,question[track]);
track++;
}
}
intmain()
{
字符标题[50];
国际音轨;
国际问题(无);
printf(“\n有多少问题?\t”);
scanf(“%d”和问题编号);
轨道=0;
char问题[问题编号][100];
而(trackscanf(“%s”)
会将字符串扫描到找到的第一块空白,因此不适合多字输入
有几种方法可以使用scanf
进行基于行的输入,但通常最好使用更容易防止缓冲区溢出的方法,例如我最喜欢的一种方法:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
全文如下:
pax> ./testprog
What? hello
OK [hello]
What? this is way too big for the input buffer
Input too long [this is w]
What?
OK []
What? exit
pax> _
使用gets(),它将输入作为一个字符串,包括空格,甚至换行符。但将一直保留到第一个换行符。与scanf()相反,scanf()占用第一个空格。我是初学者,因此无法理解。但我已将其保存在.pdf中以备将来学习。:)谢谢@paxdiablo你是一个真正的专家。我现在正在向你们学习。除了gets()不应该被使用,因为它没有缓冲区溢出保护。使用fgets()你就一切都好了。fgets()…嗯!这是一个很好的建议@Daniel谢谢!:)
pax> ./testprog
What? hello
OK [hello]
What? this is way too big for the input buffer
Input too long [this is w]
What?
OK []
What? exit
pax> _