字符串数组输出
String arrays output
如何使该程序的输出正常工作?我不知道为什么字符串数组不会存储我的值,然后在程序结束时输出它们。谢谢
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int score[100], score1 = -1;
string word[100];
do
{
score1 = score1 + 1;
cout << "Please enter a score (-1 to stop): ";
cin >> score[score1];
}
while (score[score1] != -1);
{
for (int x = 0; x < score1; x++)
{
cout << "Enter a string: ";
getline(cin,word[x]);
cin.ignore();
}
for (int x = 0; x < score1; x++)
{
cout << score[x] << "::" << word[x] << endl; // need output to be 88:: hello there.
}
}
}
我已经更正了您的代码。试试这个
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int score[100], score1 = -1;
char word[100][100];
do
{
score1++;
cout << "Please enter a score (-1 to stop): ";
cin >> score[score1];
}
while (score[score1] != -1);
cin.ignore();
for (int x = 0; x < score1; x++)
{
cout << "Enter a string: ";
cin.getline(word[x], 100);
}
for (int x = 0; x < score1; x++)
{
cout << score[x] << "::" << word[x] << endl; // need output to be 88:: hello there.
}
}
好吧,我做了什么?首先,我删除多余的{。当我第一次看到你的代码时,我不知道do.while中是有do..while循环还是while循环。接下来,我将字符串数组改为char数组,因为我知道如何从行到字符数组读取。当我需要从行到字符串读取时,我总是使用自己的函数,但如果你真的想在这里使用字符串,那就是一个很好的例子。Rest很明显。cin.ignore()是必需的,因为换行符保留在缓冲区中,所以我们需要省略它。
编辑:我刚刚找到了更好的方法来修复您的代码。一切正常,但您需要移动cin.ignore()并将其放置在while之后(score[score1]!=-1)。因为wright现在忽略了每行的第一个字符,只需要忽略用户类型-1之后的新行。固定代码。
在第一个循环中,在分配第一个值之前递增"score1"。这会将您的值放入从索引1开始的score[]数组中。然而,在下面的"for"循环中,您从0开始索引,这意味着您的分数/字符串关联将减少一。
更换
getline(cin,word[x]);
cin.ignore();
带有
cin >> word[x];
然后试着找出你哪里出了问题。
相关文章:
- 使用递归输出数组
- C++ 输出数组中的最高元素
- 空指针(为缺少的输出数组调用的 create() 在 create,文件 /home/m/OpenCV/modules/
- C++ 为什么我会得到垃圾输出数组?
- C 默认如何输出数组
- 使用递归输出数组
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 递归函数,用于输出数组的最小数量
- 如何在 c++ 中水平输出数组
- 冒泡排序未正确排序或输出数组值
- 按相反顺序输出数组的元素
- 制作一个排列函数,输出数组中所有可能的排列
- OpenCV (c++)缝合器不写入输出数组
- 创建一个3x3x3阵列.用0到9之间的随机值填充.输出数组.找出3个最小值和3个最大值的输出
- 实现[B,C]=f(A)语法(函数f作用于具有两个或多个输出数组的数组)
- 双指针输出数组参数异常
- SWIG Python C++输出数组给出'unknown type'错误
- 以 XLL 为单位获取调用方定义的输出数组尺寸
- c++:如何从函数接收可变长度的输出数组
- 未定义的符号 输出数组 opencv fedora.