While loop wont loop with inFile - c++

I'm currently writing a program that reads in a .txt file. The program is supposed to read a character, output an error, and continue reading the rest of the lines, and follow suit. I'm not sure where I'm going wrong.
#include <iostream>
#include <cmath>
#include <string>
#include <stream>
using namespace std;
int main(){
double runningTotal;
int c = 0;
string fileName;
ifstream infile;
cout << "Enter a file name\n";
cin >> fileName;
infile.open(fileName.c_str());
if (!infile.is_open()) {
cout<<"Error! invalid entry please retry!\n";
}
else {
string line;
int a, b;
while (!inflile.fail()) {
infile >> a >> b;
c = a + b;
runningTotal = c;
cout <<a<<" + "<<b<<" = " << runningTotal<<endl;
}
getline(infile, line, '\n');
if (infile.fail()){
getline(infile, line, '\n');
cout<<"stop being stupid\n";
}
}
}

Related

Assigning variables information from a infile txt C++

This is my text file:
12345 shoe 5 0
34534 foot 72 1
34562 race 10 0
34672 chicken 24 150
88 pop 65 0
I need to take this file and go row by row, assign the first number as an identifier itemNum, second word as itemName, third number as itemPrice, and last number as itemAdjusmentValue. I will need to perform arithmetic with the last two numbers itemPrice and itemAdjusmentValue.
Code so far:
using namespace std;
// making a struct to store each value of the cuadre
struct Cuadre
{
int itemNum;
string itemName;
int itemPrice;
int itemAdjusment;
};
int main (){
ifstream infile("sheet_1.txt");
string checkLine;
if (infile.is_open()){
while ( infile.good()){
getline (infile, checkLine);
cout << checkLine << endl;
}
}
else
cout << "error with name of file" << endl;
vector<Cuadre> procedures;
Cuadre line;
while(Cuadre >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment){
procedures.push_back(line);
}
This code generates an error on the last while statement
expected primary-expression before '>>' token
I cant really find a specific tutorial on how to do this, and i've looked a good amount.
From the code you posted, (with reference to the >> istream operators) it looks like you want to stream the contents of the string data read from your file into the members of a struct.
It is not possible to stream directly from a std::string (eg: checkLine >> x >> y >> z), as string does not provide a streaming interface.
In order to do that you need to use a stream, such as std::stringstream.
You could populate a with your string checkLine, and then stream from that into your data members
std::stringstream ss(checkLine);
ss >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment;
Example code:
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
// making a struct to store each value of the cuadre
struct Cuadre
{
int itemNum;
string itemName;
int itemPrice;
int itemAdjusment;
};
int main (){
ifstream infile("sheet_1.txt");
string checkLine;
vector<Cuadre> procedures;
if (infile.is_open()){
while ( infile.good()){
getline (infile, checkLine);
cout << checkLine << endl;
Cuadre line;
std::stringstream ss(checkLine);
ss >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment;
procedures.push_back(line);
}
}
else
cout << "error with name of file" << endl;
return 0;
}
You need to push into the vector inside the loop that reads from the file. And you should be getting the fields from checkLine -- Cuadre is a type name, not a variable you can read from. But to do that you need to create a stringstream.
int main (){
ifstream infile("sheet_1.txt");
string checkLine;
vector<Cuadre> procedures;
if (infile.is_open()){
while (getline (infile, checkLine)){
Cuadre line;
cout << checkLine << endl;
stringstream linestream(checkline);
if (linestream >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment) {
procedures.push_back(line);
} else {
cout << "incorrect line" << endl;
break;
}
}
}
else {
cout << "error with name of file" << endl;
}
}
while (infile.good()) is also not correct, it's essentially the same as while (!infile.eof()). See Why is iostream::eof inside a loop condition considered wrong?
You can try reading directly into struct as well:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
struct Cuadre
{
int itemNum;
std::string itemName;
int itemPrice;
int itemAdjusment;
};
int main()
{
std::vector<Cuadre> procedures;
std::ifstream infile("sheet_1.txt");
while (infile)
{
Cuadre line;
if (infile >> line.itemNum >> line.itemName >> line.itemPrice >> line.itemAdjusment)
procedures.push_back(line);
else
break;
}
if (!procedures.empty())
{
for (auto &p : procedures)
std::cout
<< "itemNum: " << p.itemNum << "\t"
<< "itemName: " << p.itemName << "\t"
<< "itemPrice: " << p.itemPrice << "\t"
<< "itemAdjusment: " << p.itemAdjusment
<< std::endl;
}
else
std::cout << "error with file or data" << std::endl;
return 0;
}
Prints:
itemNum: 12345 itemName: shoe itemPrice: 5 itemAdjusment: 0
itemNum: 34534 itemName: foot itemPrice: 72 itemAdjusment: 1
itemNum: 34562 itemName: race itemPrice: 10 itemAdjusment: 0
itemNum: 34672 itemName: chicken itemPrice: 24 itemAdjusment: 150
itemNum: 88 itemName: pop itemPrice: 65 itemAdjusment: 0
If you define an overload of >> for your type Cuadre, you can read directly from the file into Cuadre objects.
std::istream& operator>>(std::istream& is, Cuadre & cuadre)
{
std::string s;
getline(is, s);
std::cout << s;
std::stringstream ss(s);
ss >> cuadre.itemNum >> cuadre.itemName >> cuadre.itemPrice >> cuadre.itemAdjusment;
return is;
// or without logging
return is >> cuadre.itemNum >> cuadre.itemName >> cuadre.itemPrice >> cuadre.itemAdjusment;
}
int main (){
ifstream infile("sheet_1.txt");
vector<Cuadre> procedures;
for (Cuadre line; infile >> line;) {
procedures.push_back(line);
}
// or with #include <algorithm>
std::copy(std::istream_iterator<Cuadre>{ infile }, {}, std::back_inserter(procedures));
}

get() function in c++ not working for files

I wrote the following code in codeblocks and since I am new to programming I would like to know the problem in simple words. Does the open() constructor create a new file if it does not exists?
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char str[80];
cout<<"Enter a string : ";cin>>str;
int len=strlen(str);
fstream file;
file.open("TEXT",ios::in|ios::out);
for(int i=0;i<len;i++)
file.put(str[i]);
file.seekg(0);
char ch;
cout<<"\nPrintitng Contents....\n";
int k=0;
while(file)
{
file.seekg(k);
file.get(ch);
cout<<ch;
k++;
}
return 0;
}
I think you don't have "TEXT". and fstream::open don't make file when if file that you want to read do not exist.
so you may try in different stream to read and write.
following code will help you.
#include<iostream>
#include<fstream>
#include<cstring>
using namespace std;
int main()
{
char str[80];
cout << "Enter a string : ";
cin >> str;
int len = strlen(str);
ofstream fout;
fout.open("TEXT.txt");
for (int i = 0; i<len; i++)
fout.put(str[i]);
fout.close();
ifstream fin;
fin.open("TEXT.txt");
char ch;
cout << "\nPrintitng Contents....\n";
while (!fin.eof())
{
fin.get(ch);
cout << ch;
ch = NULL;
}
fin.close();
return 0;
}
and you may improve your code like this
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string str;
cout << "Enter a string : ";
cin >> str;
ofstream fout;
fout.open("TEXT.txt");
fout << str;
fout.close();
str.clear();
ifstream fin;
fin.open("TEXT.txt");
cout << "\nPrintitng Contents....\n";
fin >> str;
cout << str;
fin.close();
return 0;
}
Following code is more appropriate for C++, I think
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
string str;
string newStr;
cout << "Enter a string : "; cin >> str;
int len = str.length();
fstream file;
file.open("TEXT", ios::out| ios::in );
if (!file.is_open())
return 0;
file << str;
file.seekg(0,file.beg);
char ch;
cout << "\nPrintitng Contents....\n";
file >> newStr;
cout << newStr;
file.close();
return 0;
}

C++ reading from a .txt file line by line string and number data type on each line

So I am trying to read a .txt file in c++ program. Each line in the text file has firstName, lastName and yearlySalary (e,g, Tomm Dally, 120000).
I can seem to read a file properly - it skips the first column (firstName) and stops reading the data in after first line. Why is that?
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
string fName;
string lName;
double yearlyPay;
double backPayDue;
double newAnualSalary;
double newMonthlyWage;
int numOfEmployees = 0;
double totalBackPayDue = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (!empSalariesOld.fail())
{
while (empSalariesOld >> fName)
{
empSalariesOld >> fName >> lName >> yearlyPay;
std::cout << fName << " " << lName << " " << yearlyPay << endl;
numOfEmployees++;
}
}
empSalariesOld.close();
empSalariesNew.close();
system("pause");
return 0;
}
You are not reading the lines correctly.
When your while statement calls empSalariesOld >> fName for the first time, it reads an employee's first name. Then, inside the loop body, when you call empSalariesOld >> fName >> lName >> yearlyPay, >> fName reads the employee's last name (because you already read the first name), then >> lName reads the employee's salary, and >> yearlyPay tries to read the next employee's first name and fails!
Try something more like the following instead. Use std::getline() to read a whole line, and then use std::istringstream to parse it:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string fName;
string lName;
double yearlyPay;
//...
int numOfEmployees = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (empSalariesOld)
{
string line;
while (getline(empSalariesOld, line))
{
istringstream iss(line);
if (iss >> fName >> lName >> yearlyPay) {
std::cout << fName << " " << lName << " " << yearlyPay << endl;
++numOfEmployees;
}
}
}
empSalariesOld.close();
empSalariesNew.close();
cout << "Press any key";
cin.get();
return 0;
}
However, if the lines actually have a comma between the name and salary like you showed (Tomm Dally, 120000), then try the following instead:
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string name;
double yearlyPay;
//...
int numOfEmployees = 0;
ifstream empSalariesOld("EmpSalaries.txt");
ofstream empSalariesNew("EmpSalariesNew.txt");
if (empSalariesOld)
{
string line;
while (getline(empSalariesOld, line))
{
istringstream iss(line);
if (getline(iss, name, ',') && (iss >> yearlyPay))
std::cout << name << " " << yearlyPay << endl;
++numOfEmployees;
}
}
}
empSalariesOld.close();
empSalariesNew.close();
cout << "Press any key";
cin.get();
return 0;
}

Inserting info from a file into a struct

I want to extract data from a file and store them into the myWorld but my for loop doesn't work, the program doesn't loop one time once it gets to the for loop. I'm not sure what the problem is. This is my code so far.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
struct Country
{
double pop1950;
double pop1970;
double pop1990;
double pop2010;
double pop2015;
string name;
};
const int MAXCOUNTRIES = 300;
struct World
{
int numCountries;
Country countries[MAXCOUNTRIES];
} myWorld;
void printPop ();
int main ()
{
printPop();
return 0;
}
void printPop()
{
ifstream inFile("population.csv");
if (!inFile.fail())
{
cout << "File has opened successfully.";
}
if (inFile.fail())
{
cout << "File has failed to open.";
exit(1);
}
for (int i = 0; i < MAXCOUNTRIES; i++)
{
inFile >> myWorld.countries[i].pop1950 >> myWorld.countries[i].pop1970 >> myWorld.countries[i].pop1990
>> myWorld.countries[i].pop2010 >> myWorld.countries[i].pop2015;
getline (cin, myWorld.countries[i].name);
cout << "loop is running" << endl;
}
inFile.close();
}
I think your loop is running, its just waiting for user input here :
getline (cin, myWorld.countries[i].name);

How to read words instead of characters?

I am currently trying to read a bunch of words from a .txt document and can only manage to read the characters and display them yet. I'd like to do the same but with whole words.
My code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream infile("banned.txt");
if (!infile)
{
cout << "ERROR: ";
cout << "Can't open input file\n";
}
infile >> noskipws;
while (!infile.eof())
{
char ch;
infile >> ch;
// Useful to check that the read isn't the end of file
// - this stops an extra character being output at the end of the loop
if (!infile.eof())
{
cout << ch << endl;
}
}
system("pause");
}
Change char ch; to std::string word; and infile >> ch; to infile >> word; and you're done. Or even better do the loop like this:
std::string word;
while (infile >> word)
{
cout << word << endl;
}