c++ - 如何在循环中使用scanf,将值存储到一个变量中,然后再打印?
问题描述
我正在尝试制作一个程序,用户可以输入他们想要的测试用例的数量,输入字母的数量,然后打印它。
因为我想在i的值之后执行Cases的 printf的值与input相同的 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
这意味着第二个词scanf (2) 覆盖了它之前的值 (1)。当我希望它像这样工作时:
2
1
2
Case #1: a
Case #2: ab
我一直在谷歌搜索答案,但还没有真正找到答案。如果可能,请告诉我如何在 stdio.h 中执行此操作,以及该函数调用了什么(如递归、选择等)。非常感谢。
解决方案
首先,您需要 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 作为动态容器,并且不需要使用指针。
推荐阅读
- apache - 将Web应用程序转换为exe文件
- python - 涉及“in”和“==”的Python操作顺序
- grep - grep:查找包含单词“star”但不包含单词“start”的所有文件
- javascript - 为什么更改子组件中的状态(基于道具)会影响道具?
- docker - 如何使用桥接网络打开 docker 容器的端口
- c++ - 将一维RGB字节数组转换为c++位图
- ruby-on-rails - devise_token_auth 是否使用 JSON 网络令牌?
- mysql - 在sql中选择具有相同id的最高数字
- c - 如何在点阵 74HC595 上打开具有特定地址的 LED?
- authorize.net - 是否可以将 Accept.js 令牌与 ActiveMerchant 一起使用?