如何在循环中使用scanf,将值存储到一个变量中,然后再打印出来?

问题描述 投票:-1回答:1

我正在尝试制作一个程序,使用户能够输入他们想要的测试用例的数量,输入字母的数量,然后打印出来。

因为我要在i的值与input相同后执行Cases的printf,这意味着我必须首先保留word的值但是下一个scanf总是会覆盖前一个scanf的值。

这是我当前的代码:

#include<stdio.h>
    int main()
    {
                int input=0;
                int word=0;
                int i=0;
                int j=1;

                scanf("%d", &input);    //number of test cases

                for(i=0;i<input;i++)
                {
                    scanf("%d", &word); //how many alphabets
                }

                for(;i>0;i--)
                {
                    printf("Case #%d: ", j);
                    j++;

                    if(word==1)
                        printf("a\n"); 

                    if(word==2)
                        printf("ab\n");

                    if(word==3)
                        printf("abc\n");

                    else
                        return 0;

                return 0;
        }

例如,当前程序的工作方式如下:

2
1
2
Case #1: ab
Case #2: ab

这意味着第二个word scanf(2)将覆盖其先前的值(1)。当我希望它像这样工作时:

2
1
2
Case #1: a
Case #2: ab

我一直在Google搜索答案,但还没有真正找到答案。请告诉我如何在stdio.h中执行此操作,以及函数调用的内容(如递归,选择等)。非常感谢。

c++ stdio
1个回答
0
投票

所有人都需要用C或C ++编写此代码吗?如果您将此帖子标记为C ++,但代码是用C编写的,那么我将用C回答。

在这种情况下,您有两种解决方案:

简单的方法是在用户进行第二次输入后打印Case

#include<stdio.h>

int main()
{
    int input=0;
    int word=0;
    int i=0;

    scanf("%d", &input);    //number of test cases

    for(i = 0; i < input; i++)
    {
        scanf("%d", &word); //how many alphabets
        printf("Case #%d: ", i);

        if(word==1)
            printf("a\n"); 

        if(word==2)
            printf("ab\n");

        if(word==3)
            printf("abc\n");

    }
 return 0;
}

或者您必须建立一些动态结构来容纳所有用户输入,然后对其进行迭代并打印您的案子。在C中它将如下所示:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int input=0; 
    int i=0;
    int j=1;
    int* word = NULL;

    scanf("%d", &input);    //number of test cases

    if (input > 0) { // check if input cases are more than 0;
        word = (int*)malloc(sizeof(int) * input);
    } 

    for(i=0;i<input;i++) {
        scanf("%d", &word[i]); //how many alphabets. Write new  
    }

    for(;i > 0;i--) {
        printf("Case #%d: ", j);
        j++;

        if(word[i-1] == 1)
            printf("a\n"); 

        if(word[i-1] == 2)
            printf("ab\n");

        if(word[i-1] == 3)
            printf("abc\n");
    } 
        free(word);
        return 0;
}

如果是动态数组,则需要检查单词ptr是否不为空。但是这种情况显示了更大的前景。

如果您决定使用C ++,将会更容易,因为您可以将std :: vector用作动态容器,并且无需使用指针。

© www.soinside.com 2019 - 2024. All rights reserved.