【问题标题】:C++ Array with while loop带有while循环的C++数组
【发布时间】:2015-11-04 15:22:34
【问题描述】:

大家好,请检查此代码。我想创建一个程序,系统会提示我输入名字和姓氏,然后按时间顺序输出,而不必为每个名字和姓氏创建变量。

#include<iostream>
using namespace std;
int main(){

int fname[9];
int lname[9];
int x;

while (x < 10){
    cout<<"Enter first name: ";
    cin>>fname[0];
    cout<<"Enter last name: ";
    cin>>lname[0];
    x = x + 10;
}

x = 0;

while (x < 10){
    cout<<fname[0]<<" "<<lname[0]<<"\n";
    x = x + 1;
}

return 0;
}

【问题讨论】:

  • 为什么要使用int 数组进行文本输入?
  • while (x&lt;10){ /*...*/ x = x+10;} 将只执行一次。第二个while 循环也坏了:你写了10次相同的东西。
  • so string fname[0] = "";那么for循环呢?我需要按顺序存储数据,然后再打印。
  • @nyelnyelnyel 只需从std::vector&lt;std::string&gt;&gt; 开始,当一个简单的for 循环会更清晰时,请不要滥用while 循环

标签: c++ arrays loops


【解决方案1】:

您的数组应该是字符串类型,其余代码应如下所示:

for(int x=0;x<10;x++) {
    cout<<"Enter first name: ";
    cin>>fname[x];
    count<<"Enter last name: ";
    cin>>lname[x];
}
for(x=0;x<10;x++){
    cout<<fname[x]<<" "<<lname[x]<<"\n";
}

return 0;
}

在您自己的 sn-p 中,您将打印数组的第一个元素 10 次,这将在 x 从 0 到 9 时打印第 x 个元素。

【讨论】:

  • 我无法打印姓名。输入名称后程序滞后。 “Untitled1.exe 已停止工作”
  • 你能把你正在使用的代码贴出来吗,因为这只是我贴的一个sn-p。
猜你喜欢
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 2015-12-23
  • 2015-06-25
  • 2016-08-06
  • 2021-12-28
  • 1970-01-01
相关资源
最近更新 更多