954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ String For Loop doubling cout ..why?

Why is it, when I compile this, the cout statement runs twice at first? It does not do that when I have the rest of the code in there that is int. Any thoughts of why or what I am doing wrong..

#include
#include
using namespace std;

int main()
{

string *name;
// int *votes;
int i;
int numVotes;

cout << "how many voters: ";
cin >> numVotes;
name = new string[numVotes];

for(i=0;i < numVotes; i++){
cout <<"enter canidates last names: ";
getline(cin,name[i]);
}

for(i = 0;i < numVotes; i++){
cout << name[i] << endl;
}

//moved rest of code that's integer and not having this problem out. Basicly
//same thing, Dynamicly allocated votes of the canidates for a percentage later.

delete [] name;
system ("pause");
return 0;
}
/**************************************************************************************/
// below bit of code (unfinished mind you) does not cout repeat..don't understand.

/*votes = new int[numVotes];

for(int i = 0;i < numVotes; i++){
cout << "enter votes received : ";
cin >> votes[i];
}*/


/*for(int x=0;x<6;x++){
total = total + votes[x];
perc[x] = (votes[x] * 100) / total;
cout << "Canidate \t\t\t" << "Votes Received \t\t\t" << "% of Total Votes";
cout << name[x] << "\t\t\t\t\t" << votes[x] << "\t\t\t\t" << perc[x] << endl;
}*/
/********************************************/

//delete [] votes;

centerline00
Newbie Poster
15 posts since Oct 2010
Reputation Points: 10
Solved Threads: 0
 

Try adding this line to your program

while ((ch = cin.get()) != '\n'){}

and read this link to find out what's going on

http://www.daniweb.com/forums/thread90228.html

#include <iostream>
#include <string>
using namespace std;

int main()
{
  string *name;
  // int *votes;
  int i;
  int numVotes;
  char ch;

  cout << "how many voters: ";
  cin >> numVotes;

  name = new string[numVotes];
  
  while ((ch = cin.get()) != '\n'){}
  
  for(i = 0; i < numVotes; i++)
  {
    cout <<"enter canidates last names: ";
    getline(cin,name[i]);
  }

  for(i = 0;i < numVotes; i++)
  {
    cout << name[i] << endl;
  }
  
  return 0;
}
gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You