繁体   English   中英

您如何读取 C 中的一行字符串和 integer 输入?

[英]How can you read one line string & integer input in C?

假设我有这个程序,如果我输入“a”,将执行“a”,如果输入“b”,则执行“b”。 但是他们需要不同的东西来进行,比如“a”需要 2 个输入整数,而“b”只需要 1 个输入 integer。 因此,输入将如下所示:

8 2 // 8 is how many people and 2 is how many actions
a 2 8
b 6

我如何编写这样的程序? 就像如果“a”扫描2个整数,如果“b”扫描1个integer。 这就是我现在所拥有的:

int people, action;
char cmd[100];

scanf("%d %d", &people, &action);
for (int i = 0; i < action; i++) {
     scanf("%c", &cmd);
     if (cmd % 97 == 0) {
         #TODO
     } else if (cmd % 98 == 0) {
         #TODO
     }
}

但这不起作用,程序实际上在 i 循环时读取了 2 8 b 6 。 请帮我。

您不需要在此处使用字符 arrays。 您只需要一个字符,并且您从0 to < action而不是1 to <= action开始的 for 循环,您在这里没有使用任何 arrays,您可以直接进行。

更正在以下精炼代码中被注释掉:

int people, action;
char command; // you don't need ...[100]

int a, b, c;

printf("People <sp> Action: ");
scanf("%d %d", &people, &action);

for (int i = 1; i <= action; i++) {
    scanf("%c", &command);

    if (command == 'a') { // use this expression --- (1)
        scanf("%d %d", &a, &b); // asks for two inputs

    } else if (command == 'b') {
        scanf("%d", &c); // asks for one input

    } else {
        // To Do Else
    }
}

或者

如果你想使用 arrays 来处理int a, b, c c,那么,修改声明如下:

int a[MAX], b[MAX], c[MAX]; // const int MAX = your required number

并跳转到程序中标记的(1)部分,修改如下:

for (int i = 0; i < action; i++) { // you may use this in this situation
    .
    .
    if (command == 'a')
        scanf("%d %d", &a[i], &b[i]);
    .
    .
}

注意:您可以在循环中任何需要的地方使用break语句(例如,当command == 'b' then do TODOS and break;时。这可能对您有所帮助。

使用fgets()进行用户输入

int people, action;
char cmd[100];
int p1, p2, args;
char line[1000]; // large enough
if (!fgets(line, sizeof line, stdin)) exit(EXIT_FAILURE);
if (sscanf(line, "%d%d", &people, &action) != 2) { fprintf(stderr, "bad line\n"); exit(EXIT_FAILURE); }
for (int k = 0; k < action; k++) {
    if (!fgets(line, sizeof line, stdin)) exit(EXIT_FAILURE);
    if ((args = sscanf(line, "%c%d%d", cmd, &p1, &p2)) < 2) exit(EXIT_FAILURE);
    switch (*cmd) {
        default: exit(EXIT_FAILURE);
        case 'a': case 'A':
            if (args != 3) exit(EXIT_FAILURE);
            process_a(p1, p2);
            break;
        case 'b': case 'B':
            if (args != 2) exit(EXIT_FAILURE);
            process_b(p1);
            break;
    }
}

暂无
暂无

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

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