input spacing revisited

Earlier I posted the topic input spacing, and I've been trying to implement it with a delimiter but cannot figure it out. As I debug and step through the program, I notice that each character is not being read one after another. The program skips some characters during input, thusly not allowing c to reach my delimiter. Any ideas? This is driving me nuts.

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
33
34
35
36
37
38
39
40
41
42
int main()
{
    
 ifstream inData;
 ofstream outData;
 
 string artist[99];
 string song[99];
 char colon[99];
 char c;
 
 int i = 0;
 int j = 0;
 int x = 0;
 inData.open("songs.txt");

while(inData.get(c))
{
    if (c == ':')
    {
       x = 1;
       inData >> colon[i];
    }
                    
 if (x == 1)
 { 
    while (c != '\n')
    {
      inData >> song[j];   
      cout << song[j];
      x = 0;
     }
 }
 else
 {
 inData >> artist[i];
 cout << artist[i];
 }           
 
 i++;
 j++;
}
Last edited on
Use the getline function. Checkout the following link for an example. It works with filestreams. Instead of passing cin, as in the example, pass your input filestream object. This will read the file one line at a time as I originally suggested (including all of the white space). Then you can use std::find to search for the characters that you are using to separate fields.

http://www.cplusplus.com/reference/string/getline/

You'll also find the substr and find functions of the string class useful. find returns the position of the character you are looking for or a special value called npos if the value isn't found.
http://www.cplusplus.com/reference/string/string/

Also, do you see the # sign to the right of the edit dialogue? Please highlight your code and press that button so that code tags are inserted into your post.
Last edited on
So, I read in the first line. Then I read the artist name, then i use std::find, then I read the song name. Correct?
I just updated my previous post with another link. Before you process the string, search for your delimiter using std::string::find. That returns a number that tells you the position of the character. Then use substr by passing in 0, positionOfDelimiter-1. substr returns the new string that you can store in your array of artist names. See if you can study that documentation and figure it out. Thanks for adding the code tags and reformatting your post. It's much easier to read now. For starters, just try it with one pair of info per line in the file. Later, if you wish to get fancy you can add more songs per line and loop until all songs are processed.
NEVER MIND I FIXED IT! WOOHOO thanks for the help :-)
Last edited on
Topic archived. No new replies allowed.