user1566796
user1566796

Reputation: 35

String arrays output

How can I get the output of this program to work correctly? I'm not sure why the string array won't store my values and then output them at the end of my program. Thanks.

#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.
        }
    }

}

Upvotes: 0

Views: 7744

Answers (3)

janisz
janisz

Reputation: 6371

I've corrected your code. Try something like this

#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.
    }

}

OK what have I done? First of all I delete extra {. When I've seen your code for the first time I have no idea if there is do..while loop or while loop in do.while. Next I change string array to char array, just because I know how to read line to char array. When I need to read line to string I always use my own function, but if you really want to use string here is great example. Rest is quite obvious. cin.ignore() is required because new line character stays in buffer so we need to omit it.

EDIT: I've just found better way to fix your code. Everything is OK but you need to move cin.ignore() and place it just after while (score[score1] != -1);. Because wright now you are ignoring first char of every line and you need only ignore new line after user type -1. Fixed code.

Upvotes: 1

Luchian Grigore
Luchian Grigore

Reputation: 258558

Replace

getline(cin,word[x]);
cin.ignore();

with

cin >> word[x];

and then try figuring out where you went wrong.

Upvotes: 0

David W
David W

Reputation: 10184

In the first loop, you increment "score1" before the first value is assigned. That places your values in the score[] array starting at index 1. However, in the "for" loop below, you start your indexing at 0, meaning that your score/string associations will be off by one.

Upvotes: 0

Related Questions