字符串数组输出

String arrays output

本文关键字:输出 数组 字符串      更新时间:2023-10-16

如何使该程序的输出正常工作?我不知道为什么字符串数组不会存储我的值,然后在程序结束时输出它们。谢谢

#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];

然后试着找出你哪里出了问题。