I am trying to write a program that uses arrays and this is my first time. You have an index of 100 and then as long as you dont enter -1 the program will continue to ask you for a positive integer then once you enter -1 it asks you for a string of text to equal the amount of times you entered an integer. then it should display the answers as such:
example:
Enter a positive integer (-1 to exit): 1
Enter a positive integer (-1 to exit): 2
Enter a positive integer (-1 to exit): 3
Enter a positive integer (-1 to exit): 4
Enter a positive integer (-1 to exit): -1
Enter a string: a
Enter a string: b
Enter a string: c
Enter a string: d //enter a string shows only as much as positive integer
1 : : a
2 : : b
3 : : c
4 : : d
I don't know how to get it show up the way the example does, all I get is this:
Enter a positive integer (-1 to exit): 1
Enter a positive integer (-1 to exit): 2
Enter a positive integer (-1 to exit): 3
Enter a positive integer (-1 to exit): 4
Enter a positive integer (-1 to exit): -1
Enter a string: Enter a string: a
Enter a string: b
Enter a string: c // just keeps repeating this
Press any key to continue...
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string string;
int integer[100];
int integerVar = -1; //integerVar is array index "I think". Stands for integer variable
do
{
integerVar = integerVar + 1;
if (integerVar > 100)
{
cout << "Highest possible amount is 100";
break;
}
cout << "Enter a positive integer (-1 to exit): ";
cin >> integer[integerVar];
}
while (integer[integerVar] != -1);
for (int counter=0; counter<integer[integerVar]; counter=counter=1)
{
cout << "Enter a string: ";
getline(cin, string);
} // I though this for statement would make string show up only as much as the integer question
cout << integerVar << " : : " << string << endl;
}
1)in for loop use counter<integerVar
2)use counter++
3)If you are entering only characters than don't use string .(also how can string string; be valid type?)
4)use cin.ignore(); before for loop to get first input.
5)if you have to get only char then add each char in string type
6)for desired output you will require for loop to show output.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string string;
int integer[100];
int integerVar=-1;
do
{
integerVar = integerVar + 1;
if (integerVar > 100)
{
cout << "Highest possible amount is 100";
break;
}
cout << "Enter a positive integer (-1 to exit): ";
cin >> integer[integerVar];
}
while (integer[integerVar] != -1);
// here is the revised part
cin.ignore();
for (int counter=0; counter<integerVar; counter=counter+1)
{
cout << "Enter a string: ";
getline(cin, string);
}
The problem is that you are using the same string to store all the strings in so only the last one is remembered. You could use a similar method as in the first loop but instead use an array of strings.