调用数组存储字符串类型从一个while到另一个while
Call array storing string type from one while to another
如何修复代码?我不能用向量。我需要能够调用第一个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指定的新计数是一个很好的做法。为什么我的答案有效却被否决了?
相关文章:
- 用于在 C++ 中使用 while 循环查找下一个素数的简单函数
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 如何创建一个 while 循环,继续循环,直到在C++中输入'using streams'键?
- 有没有办法制作一个 c++ 宏(或类似的东西),它使用户语句被 while 循环的预定义函数包围?
- 为什么其中一个 while 循环没有被执行 (C++)?
- 为什么这个do-while循环每隔一个循环只写入数组?
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 如何将一个 while 循环与 for 循环组合在一起?
- 如何在while循环之外分配一个新值
- C++创建一个类似于 while、if 或 for 的函数
- while 循环在一个函数调用中执行两次
- 对我是否需要一个哨兵值来终止我的 do while 循环以允许多个条目感到困惑
- C++:C字符串、指针和一个非常有趣的while循环
- C++使用cin.get来获取一个字符,但在遇到EOF时不会结束while循环
- 两个输入进入一个 while 循环
- 我在不使用string.h的情况下写了一个C++回文.在没有 Do-While 循环的情况下,它可以正常工作.但是当我尝
- For 或 While 循环具有 2 个最大变量,其中一个是数组(编程 I)
- 在的内部插入while循环.把这看作一个脑筋急转弯
- 更改了bool值,但在while语句的下一个循环中它又变了回来
- 使用do while擦除一个向量中的元素并将其添加到另一个向量