调用数组存储字符串类型从一个while到另一个while

Call array storing string type from one while to another

本文关键字:while 一个 另一个 存储 数组 字符串 类型 调用      更新时间:2023-10-16

如何修复代码?我不能用向量。我需要能够调用第一个while到第二个while的课程名称并显示它们。

cout << "Please enter the number of classes"<< endl;//Number of classes for the while
    cin >> nclass;
while (count <= nclass ) // while
{
    //Information for the class
    {
        cout << "Please enter the course name for the class # "<< count << endl;
            getline (cin, name);
        string name;
        string coursename[nclass];
        for (int i = 0; i < nclass; i++) {
            coursename[i] = name;
        }
    }
    char choose;
    cin >> choose;
    while ( choose == 'B' || choose == 'b') {//Name the courses
        for (int x = 0; x < nclass; x++){
            cout << "Here is a list of all the courses: n" << coursename[i] << endl;
        }
        return 0 ;
    }

您正在声明coursename作为局部内循环,然后在外部使用它,因此您会得到编译时错误(coursename是未声明的标识符)。

一个问题:内部for循环的作用是什么????!!

在while循环中使用for循环,通过它为所有元素分配与字符串名称相同的值!!因此,每当count增加时,内部for循环在赋值后将name的新值赋给coursename的所有元素。

count未定义!因此,声明它并将其初始化为1或0,并记住这一点。

你写信给coursname: count <= NCLSS的出界来纠正它:

while(count < nclass)...

另一个重要的事情:清除输入缓冲区,使cin为下一个输入做好准备。与cin。忽略或sin.sync

cout << "Please enter the number of classes"<< endl;//Number of classes for the while
cin >> nclass;
string coursename[nclass];
int count = 0;
while (count < nclass ) // while
{
    //Information for the class
    string name;
    cout << "Please enter the course name for the class # "<< count << endl;
    cin.ignore(1, 'n');
    getline (cin, name);
    coursename[count] = name;
    cin.ignore(1, 'n');
    count++;
}
char choose;
cin >> choose;
while ( choose == 'B' || choose == 'b') {//Name the courses
    for (int x = 0; x < nclass; x++){
        cout << "Here is a list of all the courses: n" << coursename[x] << endl;
    }

代码正常运行!

#include <iostream>
#include <string>
using namespace std;

int main()
{
    int nclass = 0, count = 1, countn = 1;
    string name[100];
    cout << "Please enter the number of classes" << endl;
    cin >> nclass;
   while (count <= nclass) {
      cout << "Please enter the course name for the class # " << count << endl;
      cin >> name[count];
      count++;
      }
    cout << "Here is a list of all the courses: " << endl;
    while (countn <= nclass) {
        cout << name[countn] << endl;
       countn++;
   }
    return 0;
}

注意,数组name的大小为100。没有人会有100节课!没有必要使用for循环。初始化计数和由countn指定的新计数是一个很好的做法。为什么我的答案有效却被否决了?

相关文章: