While loops + strings

I want to write a program that allow the console to take in any number of names, and then output the names and the number of names input. The problem is, I want to do this in a while loop, but for some reason, I can't get it to work with strings. Any ideas?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main(){
	int counter = 0, i = 0;
	string signature[100];

	ofstream outData;


	while (signature != "Exit"){
		cout << "Please input your electronic signature: ";;
		cin >> signature[i];
		counter++;
	}

	outData.open("sigFinal.txt");

	for (i = 0; i < counter; i++){
		outData << signature[i] << endl;
	}
	outData << counter;

	for (i = 0; i < counter; i++){
		cout << signature[i] << endl;
	}
	cout << counter;

	return 0;
}
you cannot compare an array signature and a string "exit"
Ok so how could I fix the problem?
As shadowCODE said, you need to check if the LAST element entered is "Exit" instead.

1
2
3
4
5
while (counter > 0 && signature[counter-1] != "Exit"){
		cout << "Please input your electronic signature: ";;
		cin >> signature[counter]; // You never increment i
		counter++; // But you increment counter
	}


or if you dislike that extra counter > 0 check

1
2
3
4
5
     do {
		cout << "Please input your electronic signature: ";;
		cin >> signature[counter];
		counter++;
	} while (signature[counter-1] != "Exit");


Notice that I changed cin >> signature[i] to signature[counter] since that is the variable that you incremented. In addition, the check is for counter-1 because you care about the last element while counter is the index to the "new" element that is about to be entered.

Hopefully that helped. Feel free to ask for clarification.
Last edited on
Topic archived. No new replies allowed.