Why won't my first character show up?

Hi. Writing a program that reads multiple strings into a vector, displays them, then does some other stuff to them. The problem is that the first character of the string won't show up. (following excerpt is not complete program)


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

void read_string(vector<string> &v);
void display_string(const vector<string> & v);
void string_reverse(vector<string> & v);
void sort_string();
void displayASCII();

int main()
{
vector<string> G;
read_string(G);
display_string(G);

return (0);
}

void read_string(vector<string> & v)
{
string i;
cout << "Enter a string (ending with '.'): " << endl;
cin >> i;
while (i != ".")
{
cin >> i;
v.push_back(i);
}
}
void display_string(const vector<string> & v)
{
for (int i = 0; i < v.size(); i++)
{
cout << v[i];
}
cout << " " << endl;
}


Input: a b c d 1 2 3 4

Program outputs: bcd1234 (no a!!!!) Why?
I've tried all sorts of things. Most recently, running the display loop from i = 1 and outputting v[i-1].
Well the first time you get something into the i variable you are not saving it into the vector.
1
2
3
4
5
6
7
8
cout << "Enter a string (ending with '.'): " << endl;
cin >> i; //**************this entry is not being saved 
while (i != ".")
{
cin >> i;
v.push_back(i);
}
}


EDIT:
I might as well add that the firs t cin>> i is redundant anyway - because the default
constructor for string creates an empty string which wil not be equal to . so the loop will run - OR
you could create the string with some string value that is not equal to .

So - this will do the job.
1
2
3
4
5
6
7
8
9
string i; //the default constructor creates an empty string 
cout << "Enter a string (ending with '.'): " << endl;
//cin >> i; //get rid of this line -  it is redundant.
while (i != ".")
{
cin >> i;
v.push_back(i);
}
}

Last edited on
Well. That makes sense. Thank you.

Topic archived. No new replies allowed.