I am trying to read from a input file for a bookstore the books information. I have used getline for reading the file, however, some books have two authors and two different formats, and this is where i am stuck. I need my output to have both names listed as authors and both formats correct, my output is fine until I reach the authors point and also my formats arent correct. Below is the txt file and code I have so far. Some declared variables are for the rest of the program.
**C++ Code:**
string str;
string title;
string authors[4];
string publisher;
string ISBN;
string filename;
string Format;
double cost;
int yearpublished;
int copies;
int numOfcopies;
int numOfauthors;
int numFormats;
char userChoice;
int count = 0;
int num = 0;
int input = 0;
ifstream infile;
int i;
cout << "please enter the name of the file you wish to input:" << endl;
getline(cin, filename);
infile.open(filename.c_str());
if (!infile) {
cout << "file not found!!!" << endl;
exit(0);
}
while (!infile.eof()) {
getline(infile, title);
cout << "Title: " << title <<endl;
getline(infile, ISBN);
cout << "ISBN: " << ISBN << endl;
getline(infile, publisher);
cout << "publisher:" << publisher << endl;
string yearpublished;
getline(infile, yearpublished);
cout << "Year published: " << yearpublished << endl;
string cost;
getline(infile, cost);
cout << "Price:" << cost << endl;
string numOfcopies;
getline(infile, numOfcopies);
cout << "Copies in stock:" << numOfcopies << endl;
string numOfauthors;
getline(infile, numOfauthors);
cout << "Number of authors: " << numOfauthors << endl;
getline(infile, authors[4]);
cout << "Book authors:" << authors[4] << endl;
string numFormats;
getline(infile, numFormats);
cout << "Number of formats:" << numFormats << endl;
getline(infile, Format);
cout << "Book format:" << Format << endl;
string NumPages;
getline(infile, NumPages);
cout << "Number of Pages:" << NumPages << endl;
Look into std::vector. This allows you to have a variable sized array. After you have retrieved the amount of authors, you can use a for loop with getline to get the correct amount of authors. Or you put them all on one line with a separator like a comma to split them like demonstrated here:
Parse (split) a string in C++ using string delimiter (standard C++)
You can push the individual names into the vector.
my assignment is to take a string from a text file and count the number of words in it. I've gotten that far but now we have to be able to take a certain number and display that number word to the console. Say my string is "Hello World" if I enter '2' it should give me the result "World". I'm not really sure how my function should look for this. This is my code so far.
void getFileInfo(ifstream &inFile);
string words(ifstream &inFile);
int numOfWords(ifstream& inFile);
int main() {
ifstream inFile;
string sentence, fileName;
int numCount, word;
getFileInfo(inFile);
numCount = numOfWords(inFile);
inFile.clear(); // resets file pointer from the beginning
inFile.seekg( 0 );
sentence = words(inFile);
cout << sentence << ": has " << numCount << " words in it" << endl;
cout << "Enter a number to extract a word: ";
cin >> word;
}
void getFileInfo(ifstream &inFile){
string fileName;
do{
cout << "Please enter the filename: " << endl;
cin >> fileName;
inFile.open(fileName.c_str());
if(!inFile){
cout << "Invalid try again" << endl;
}
}while(!inFile);
}
string words(ifstream &inFile){
string words, theWords;
getline(inFile, words);
cout << words;
return theWords;
}
int numOfWords(ifstream& inFile){
string fileName, words, str;
int numCount =0;
while(inFile >> words){
++numCount;
}
return numCount;
}
Any suggestions?
Thanks in advance
I would suggest slightly different code for your task. First, write some simple helper functions:
// Clear error flags (EOF, for example) and reset stream to the beginning.
void resetStream(ifstream& stream) {
stream.clear();
stream.seekg(0, ios_base::beg);
}
// Count the words in text file stream.
int getWordsCount(ifstream& stream) {
int count = 0;
while (stream) {
string tmp;
stream >> tmp;
if (!tmp.empty()) ++count;
}
resetStream(stream);
return count;
}
// Read word by specific number.
string getWordByNumber(int number, ifstream& stream) {
string word;
while (number--)
stream >> word;
resetStream(stream);
return word;
}
Now you can easily get the number of words in a file and display a specific word by its number. For example:
int main() {
string fileName;
cout << "Enter the file name: \n";
cin >> fileName;
ifstream stream(fileName);
if (!stream)
cout << "Failed to open file!" << endl;
else {
int totalCount = getWordsCount(stream);
int currentCount = 0;
cout << "Total words count: " << totalCount << "\n\n";
do {
cout << "Enter the word number (enter '0' to finish): ";
cin >> currentCount;
if (currentCount == 0) break;
else if (currentCount > totalCount)
cout << "Invalid value!\n";
else {
string wordByNumber = getWordByNumber(currentCount, stream);
cout << "Word by number: " << "'" << wordByNumber << "'\n";
}
cout << "\n";
}
while (true);
}
return 0;
}
Warning: This code is not very efficient and I have not tested it much. If you have any problems, be sure to write a comment.
I need this program to show the count of words from a file (text document). However, not reseting counter of words. its supposed to be 7 but it is displaying 62 words. I was told to close the file from the second last while and create a new while (which is the last one) and open the file again. I've working on this for a while. However, after making the changes it doesn't display the file anymore. the only thing display in the screen it s a th and account of 2 words.
Thanks for your help
#include<iostream>
#include<fstream>//step#1
#include<string>
using namespace std;
int main()
{
string word,fileName;
char character;
int charcounter = 0, wordcounter = 0;
ifstream inData;// incoming file stream variable
cout << " Enter filename or type quit to exit: ";
cin >> fileName;
//loop to allow for multiple files data reads
while (fileName != "quit")
{
inData.open(fileName.c_str());//open file and bind file to ifstream variable
//loop for file not found validation
while (!inData)//filestream is in fail state due to no file
{
inData.clear();//clear the fail state
cout <<"File not found. Enter the correct filename: ";
cin >> fileName;
inData.open(fileName.c_str());
}
inData >> character;//extract a single character from the file
cout << "\n*****************************\n";
while (inData)
{
cout << character;
inData.get(character);
charcounter++;
}
cout << "\n******************************\n";
cout << fileName << " has " << charcounter << " words." << endl;
inData.close();//close the ifstream conection to the data file
while (inData)
{
cout << word;
wordcounter++;
inData.open(fileName.c_str());
}
charcounter = 0; //reset character count
wordcounter = 0;
//port for next file or exit
cout << "Enter a filename or type quit to exit: ";
cin >> fileName;
}
return 0;
}
Do you want this?
#include<iostream>
#include<fstream>//step#1
#include<string>
using namespace std;
int main() {
string word,fileName;
char character;
int charcounter = 0, wordcounter = 0;
ifstream inData;// incoming file stream variable
cout << " Enter filename or type quit to exit: ";
cin >> fileName;
//loop to allow for multiple files data reads
while (fileName != "quit")
{
inData.open(fileName.c_str());//open file and bind file to ifstream variable
//loop for file not found validation
while (!inData)//filestream is in fail state due to no file
{
inData.clear();//clear the fail state
cout <<"File not found. Enter the correct filename: ";
cin >> fileName;
inData.open(fileName.c_str());
}
cout << "\n*****************************\n";
while (inData)
{
inData >> character;//extract a single character from the file
cout << character;
charcounter++;
}
cout << "\n******************************\n";
cout << fileName << " has " << charcounter << " chars." << endl;
inData.close();//close the ifstream conection to the data file
inData.open(fileName.c_str());
while (inData)
{
inData >> word;
cout << word;
wordcounter++;
}
cout << "\n******************************\n";
cout << fileName << " has " << wordcounter << " words." << endl;
inData.close();//close the ifstream conection to the data file
charcounter = 0; //reset character count
wordcounter = 0;
//port for next file or exit
cout << "Enter a filename or type quit to exit: ";
cin >> fileName;
}
return 0;
}
I'm currently taking an online C++ class and our current project requires us to read a file, take each student and put it into a vector.
My current problem is splitting the name read and setting it to the right variables.
The professor's pseudo code here:
inputFile.open(sFileName.c_str ());
while(inputFile.fail())
{
cout ERROR OPENING FILE
cout PLEASE REENTER THE PASSWORD OF THE FILE
getline(cin >> wd, sFileName);
inputFile.open(sFileName.c_str());
}
inputFile.clear();
inputFile.seek(0, ios::beg);
while(getline(inputFile, sTemp))
{
istringstream inputSStream(sTemp)
inputSStream >> sFirstName >> sMiddleName >> sLastName >> sID >> sClass;
if(sMiddleName != "|")
sFullName = sFirst name + " " + sMiddleName +" " + sLastName;
else
sFullName = sFirstName + " " + sLastName;
My current code here:
ifstream myFile;
string firstName, middleName, lastName, fullName, studentID, cID;
string inFileName, stringTemp;
cout << "Please enter the name of the file that you want to read in. \n";
cin >> inFileName;
myFile.open(inFileName);
while (myFile.fail())
{
cout << "\n""";
cout << "Error file, Please re-enter file. \n ";
cin >> inFileName;
myFile.open(inFileName);
}
myFile.clear();
myFile.seekg(0, ios::beg);
while (getline(myFile, stringTemp))
{
istringstream inputStream(stringTemp);
inputStream >> firstName >> middleName >> lastName >> studentID >> cID;
if (middleName != "|")
fullName = firstName + " " + middleName + " " + lastName;
else
fullName = firstName + " " + lastName;
//Checking what the input values are
cout << "First name is " << firstName << endl;
cout << "Middle name name is " << middleName << endl;
cout << "Last name is " << lastName << endl;
cout << "studentID is " << studentID << endl;
cout << "CID is " << cID << endl;
Student thisStudent(fullName, studentID, cID);
studentList.push_back(thisStudent);
}
myFile.close();
The current problem is that the line isn't split correctly, first name gets the whole line and mid and last name, studentID and cID all remain empty.
Here is the current file that I'm reading in:
ERIC,ANTHONY,TURNER,1234573,CISC_198
GABRIEL,FEIJO,LOPES,1234574,CISC_199
GEOFFERY,BRYAN,RANSOM,1234575,CISC_200
HANNAH,MAE ,LONGRIE,1234576,CISC_201
HASSAN,ISMAIL,AHMED,1234577,CISC_202
HUNG,B,PHAM,1234578,CISC_203
HUSSEIN,FOUAD,ALJANABI,1234579,CISC_204
JING,XUN,CHEN,1234580,CISC_205
KAJALBEN,CHIMANLAL,MAKWANA,1234581,CISC_206
DANDREA,SHAMAICAH,BUSH,1234570,CISC_195
DANIELLE,MARIE,CORTEZ,1234571,CISC_196
ERDI,T,KIDANE,1234572,CISC_197
AARON,FABIAN,LINGAD,1234567,CISC_192
AARON,T,PATCHIN,1234568,CISC_193
ALI,FOUAD,ALJANABI,1234569,CISC_194
NATHAN,|,NANN,1234585,CISC_210
NEIL,ANDREAS,FRANKA,1234586,CISC_211
OBONE,|,ORIYAVONG,1234587,CISC_212
OLIVIA,JOANNE,MAILANDER,1234588,CISC_213
RALEIGH,|,COSGROVE,1234589,CISC_214
RYAN,PAREDES,PALMARES,1234590,CISC_215
MICHAEL,DUONG,NGUYEN,1234583,CISC_208
MIGLENA,|,CHEMELEKOVA,1234584,CISC_209
STEPHEN,MICHAEL,HOUSE,1234591,CISC_216
MARCUS,D,BUTLER,1234582,CISC_207
Here is the output that I do not understand how to fix.
First name is ERIC,ANTHONY,TURNER,1234573,CISC_198
Middle name name is
Last name is
studentID is
CID is
When you read with operator >> you are splitting on whitespace. Despite the name, getline() can split by other characters than newline:
getline(inputStream, firstName, ',');
getline(inputStream, middleName, ',');
// ...
I have a test file ("InputFile.txt") saved with some random information as well as a blank output file ("output.txt"). When I debug the program and check the output file, it's still blank.
Should "output.out" be "output.txt" (line 25)? Am I having problems because I have "InputFile.txt" as a cstring at line 22 in the if statement?
Is this correct otherwise? I'm sort of lost when it comes to fstream so far, please help.
My code:
#include<fstream>
#include<string>
#include<iomanip>
#include<iostream>
using namespace std;
int main()
{
ifstream InputFile;
ofstream OutputFile;
string lastName, firstName, fileName,
line;
int creditHours, state;
int tuition;
bool valid = false;
do{
cout << "Input file name (.txt): ";
cin >> fileName;
if(fileName == "InputFile.txt")
{
InputFile.open("InputFile.txt");
OutputFile.open("output.out");
valid = true;
}
else{
cout << "Invalid file name/type." << endl;
}
}while(valid == false);
OutputFile << "Last Name: " << ' ' << "First Name: " << ' '
<< "Credit Hours: " << ' ' << "Tuition Amount: " << endl;
while(!InputFile.eof()){
getline(cin, line);
InputFile >> firstName >> lastName >> creditHours >> state;
if(state == 1)
{
tuition = (creditHours * 350);
}
else
{
tuition = (creditHours * 570);
}
OutputFile << lastName << ' ' << firstName << ' '
<< creditHours << ' ' << tuition << endl;
}
InputFile.close();
OutputFile.close();
return 0;
}
Try this
ifstream inFile;
ofstream outFile;
and open your file in and out mode like
inFile.open("InputFile.txt", ios::in);
outFile.open("Output.txt",ios::out);
after that read Inputfile data and write it into output file
while (!inFile.eof()) {
inFile >> firstName >> lastName >> creditHours >> state;
outFile << firstName << " " << lastName<<" "<<creditHours<< " " <<state<<" "<< endl;
}
and apply logic within loop own way