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.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace 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!
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?