如何在C中输入多字符串

时间:2013-11-19 06:40:03

标签: c string multidimensional-array

我有这个程序。我想在二维数组中输入多字符串。但是不是在2-D数组的第一个数组中输入整个字符串,而是在每个前三个数组中输入我的String的前三个单词(因为我在我的2-D数组中定义了行数)。这是程序:

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

这里“question_no”是我想在我的2-D数组中输入的字符串 - “问题”。但是当我输入第一个字符串时,字符串的前三个字在三个二维数组中输入。它甚至不要求我输入第二或第三个字符串。

我认为,这个问题的解决方案应该是三维数组。因为这样,最外层数组中的2-D数组将打印整个多字符串(但我也认为,每个字符串的长度也是如此)。如果这样,三维数组概念,可以解决问题,那么还有一些有效的方法吗?这比3-D阵列方法更好,更快,更省时。

2 个答案:

答案 0 :(得分:1)

scanf("%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;
}

这是一个方便的例程,它提供基于行的输入,缓冲区溢出保护,检测太长的行,清理这些行,以便它们不会影响下一个输入操作和提示。

测试程序如下所示:

int main (void) {
    int rc;
    char buff[10] = "";

    while ( 1) {
        rc = getLine ("\nWhat? ", buff, sizeof(buff));
        if (rc == NO_INPUT) {
            // Extra NL since my system doesn't output that on EOF.
            printf ("\nNo input\n");
            return 1;
        }

        if (rc == TOO_LONG) {
            printf ("Input too long [%s]\n", buff);
            continue;
        }

        if ( strcmp (buff, "exit") == 0)
            break;
        printf ("OK [%s]\n", buff);
    }

    return 0;
}

成绩单如下:

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> _

答案 1 :(得分:0)

使用gets(),这将输入作为包含空格的一个字符串,甚至是换行符。但是直到第一个换行才会进入。而不是scanf(),它占用了第一个空格。