Trouble with fstream

I'm working on this project that has me read the word in front of the first three commas in a text file the user inputs the name to. I'm getting the program to output the first few letters of the word in front of the comma but doesnt work very well. This is what i have so far.

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
    string fileText;
    string fileName;
    ifstream inData;
    ofstream outData;
    int index;

    outData.open("fixedWords.txt");

    cout << "Please enter the name of your file "
         << "followed by the (enter) key." << endl;
    cin >> fileName;

    inData.open(fileName.c_str());
    getline(inData, fileText);

    
    index = fileText.find(',');     //assigned value of 3

    //starts from position 3 in the string and prints until a blank char
    outData << fileText.substr(index + 1, fileText.find(' '));
    
    

    return 0;
}


1
2
//input file name is be.txt
Hey, what's up? Not much, you know, just hanging.  


1
2
//output file text is fixedWords.txt
 wha //white space before the text 


The only thing that i can think of is that by creating a substring that starts one character ahead of where the comma is, in the string, and then assigning the end to be where the first blank char appears in the string might be causing something funky. Any insight would be helpful. Thanks in advance!
Last edited on
I'm not sure I quite understand the problem. What is the output text supposed to look like?
1
2
3
what's
you
just 

so output the word in front of the three commas from the input text file
Did you print out what fileText.find(' ') returned?

You're using substr incorrectly. It takes two numbers: the index to start at, and the number of characters to copy. You are starting at the correct index, and then copying fileText.find(' ') number of characters. fileText.find(' ') returns 4, the position it first finds a space.

You say the problem asks you to find the word BEFORE the commas, but those three words in your last comment are the ones AFTER the commas. Which one is it?
Topic archived. No new replies allowed.