For full disclosure this is an assignment for my programming class and I just want tips or advice on some of the code.
Assignment details just for background information purposes.
Write a program that will read a number 1-100 from the user, and the name of a data file, and will tell the user what word is in the file and how many times the numbers shows up in the data file. Validate input number (keep asking until valid) and validate the file was successfully open.
text file contents: Darling 10 20 21 19 20
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> // Needed for exit()
using namespace std;
int main()
{
ifstream inputFile;
string fileName;
int value;
cout << "Enter the file name: ";
getline(cin, fileName);
// Open the file
inputFile.open(fileName.c_str());
// Check for successful opening
if(inputFile.fail())
{
cerr << "Error Opening File" << endl;
exit(1);
}
cout << "\nThe file has been successfully opened for reading.\n";
cout << "Pick a number between 1 through 100. ";
cin >> value;
if (value >= 1 && value <= 100)
{
cout << value << " is in the acceptable range.\n";
}
else
{
cout << "Please enter a number from 1 to 100. ";
cin >> value;
}
string word;
int number;
int count = 0;
infile >> number;
// Read a file until you've reached the end
while (!inputFile.eof())
{
if (number == x)
{
sum1++
}
infile >> number;
}
cout << sum1;
while (!inputFile.eof())
{
inputFile >> word;
if (word == "input")
{
count++;
}
}
// Close the file
inputFile.close();
return 0;
}
Any tips or advice would be greatly appreciated since I'm lost when it comes to the fstream portion of this assignment right now.
Thanks in advance,
James
Related
Hey I am trying to figure out how to access an a object out of the scope of the block. I defined Person personData in the For loop which writes data to the file. And after the loop I wanted to access the object again to update the values on the file but its giving me the error - personData is undefined identifier.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <cstdlib>
#include "Person.h"
using namespace std;
int main() {
string lastName;
string firstName;
int age;
//file output and creation
ofstream outPerson("nameage.dat", ios::out | ios::binary);
Person randPerson;
randPerson.setLastName("unassigned");
randPerson.setFirstName("");
randPerson.setAge(0);
randPerson.setId(0);
//for loop to initialize the file with 100 records that store values lastName and firstName
for (int i = 0; i < 100; i++) {
outPerson.write(reinterpret_cast<const char*>(&randPerson), sizeof(Person)); //use write to output to file
}
cout << "File Created" << endl;
//file input and termination
ifstream inPerson("nameage.dat", ios::in | ios::out | ios::binary);
//loops through 10 times to input 10 values (RECORD VALUES)
for (int j = 0; j < 2; j++) {
int id = 0;
do {
cout << "Enter a valid id number: (1-100)" << endl;
cin >> id;
} while ((id<1)||(id>100)); //breaks do-while after it receives a valid input
Person personData;
inPerson.seekg((id - 1) * sizeof(Person));
inPerson.read(reinterpret_cast<char*>(&personData), sizeof(Person));
//checks to see if there is already data in that area, if not then proceed to record data onto file
if (personData.getId() == 0) {
cout << "Enter lastname: ";
cin >> lastName;
cout << "Enter firstname: ";
cin >> firstName;
cout << "Enter age: ";
cin >> age;
//sets data for the particular object
personData.setLastName(lastName);
personData.setFirstName(firstName);
personData.setAge(age);
personData.setId(id);
//seek position in file of user-specified record
outPerson.seekp((personData.getId() - 1) * sizeof(Person));
//write user-specified information in file
outPerson.write(reinterpret_cast<const char*>(&personData), sizeof(Person));
cout << "Record inserted" << endl;
}
else {
cout << "There is already data there. Try another ID number" << endl;
}//end if
}//end for loop
int idSearch;
do {
cout << "Enter a ID number: " << endl;
cin >> idSearch;
} while ((idSearch < 1) || (idSearch > 100));
if (personData.getId() != 0) {
cout << "Enter new Last name";
cin >> lastName;
cout << "Enter new first name";
cin >> firstName;
cout << "Enter age";
cin >> age;
//sets data for the particular object
personData.setLastName(lastName);
personData.setFirstName(firstName);
personData.setAge(age);
personData.setId(idSearch);
//seek position in file of user-specified record
outPerson.seekp((personData.getId() - 1) * sizeof(Person));
//write user-specified information in file
outPerson.write(reinterpret_cast<const char*>(&personData), sizeof(Person));
cout << "Record updated" << endl;
}
inPerson.read(reinterpret_cast<char*>(&personData), sizeof(Person));
system("pause");
return 0;
}
I'm assuming the problem is because the object cant be accessed when out of scope. So how would I go about accessing the object from the statement below the for loop. Thank you.
It's one of the core ideas of C++ data model: data is deleted as soon, as it leaves the scope.
For this to work, you'd need to change the scope of personData (for example, move variable definition outside of the loop).
But be cautious using something like that. In the very best case personData would store data left by the last iteration of the loop.
I'm working on the following problem:
I need to write a prgoram that reads an ASCII text file from the hard drive and allows the user to display and edit the contents of the file line-by-line.
It must have the following features:
It reads the file name from the standard output and opens the text file using a file stream.
When the file is loaded, the user enters the text line number.
If the line exists, it is displayed in the standard output.
If the line does not exist (the user has entered a line number
that is greater than the number of lines in the file), an error message is displayed,
for example: The line 82 does not exist. When the line is displayed the user is given
an option to enter a new string in the standard input that will become the contents of
the line. The string can contain blank spaces. Then the user is asked to enter another line number.
Finally, the user is asked whether he wants to save the changes in the file or not.
Technical requirements: The program must be composed by more than one function
This is my code so far:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
void printErrorMessage(int lineNumber)
{
cout << endl << " ERROR: The line " << lineNumber << " does not exist"
<< endl;
}
int main()
{
int line_number;
vector<string> TextVector;
int loop = 1;
fstream myfile;
myfile.open("test.txt", std::fstream::in | std::fstream::out);
while(loop == 1)
{
if (myfile.is_open())
{
// get end line of file.
cout << "File has opened successfully." << endl;
}
else
{
cout << "File hasn't opened successfully.";
return 0;
}
cout << "Enter the text line number:" << endl;
cin >> line_number;
size_t lines_count = 0;
string line;
while(getline(myfile, line))
{
TextVector.push_back(line); // push to text file
}
if(line_number > TextVector.size() + 1)
{
printErrorMessage(line_number);
return 0;
}
cout << TextVector[line_number] << endl;
cout << "If you'd like to change the line, please enter it, otherwise enter n to exit" << endl;
string changeLine;
getline(cin, changeLine);
if (changeLine == "n")
{
myfile.close();
return 0;
}
TextVector[line_number] = changeLine; // changes the line with the new string
cout << "Would you like to enter a new line to edit? (Y/n)" << endl;
string newLine;
cin >> newLine;
if (newLine != "y" && newLine != "Y")
{
cout << "Would you like to save all your changes to the file? (Y/n)" << endl;
string saveChanges;
cin >> saveChanges;
if (saveChanges != "y" && saveChanges != "Y")
{
myfile.close();
return 0;
}
for (int i = 0; i < TextVector.size() + 1; i++)
{
cout << TextVector[i] << endl;
myfile << TextVector[i] << endl;
myfile.flush();
}
myfile.close();
return 0;
}
}
return 0;
}
Technically I do save the changes to the vector, but for some reason I cannot get to overwrite the vector into the text file that already is full.
Also, any idea why the
getline(cin, changeLine);
Still acts as if it's a normal string? shouldn't it get the whole line entered togethe with the spaces?
Some guidance would really be appreciated!
#include <iostream>
#include <fstream>
using namespace std;
void get_input (ifstream& ifile){
std::string filename;
cout << "Input filename:";
cin >> filename;
if (ifile.fail()){
cout << "File is not found"<< endl;
}
int ID, score, count = 0;
while (1){
ifile >> ID >> score;
if (ifile.eof()) break;
++count;
}
ifile.close();
cout << ID << endl;
cout << count << endl;
cout << score << endl;
}
main:
int main(int argc, const char * argv[]) {
ifstream file;
get_input (file);
return 0;
}
I changed it to std::string, but the counter still prints out 0. I am taking int data from a file that has 2 columns. I also need to count the number of lines in the file.
You have more than one problem.
As someone else mentioned, you're not actually opening any file.
if (ifile.fail()) <<this is failing & does not get entered
Instead try
if (!ifile.is_open())
And it will show that you're not opening anything.
Once you open the file like so;
ifile.open(filename);
Your code should work, however I can't see where you're checking for line returns. I'll leave that as an exercise for you to follow up. Try searching for std::getline.
i have to write a code that prompts user to enter a file name (containing 2 columns of integer). The program then reads that file, prints out the numbers set.
My txt file looks like this (the numbers are separated by space):
2 3
5 6
7 8
8 9
5 7
I thought it would be easy, but now i stuck. When i run the program, this line appeared
"There're no number in the file."
I set number to "int", so why can't the compiler read the number? But when i change the type to "string", the numbers did appear O_O , since i later need to calculate the average of those num also, i cannot use string.
Here is my code, I appreciate any help TT___TT
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
ifstream in_file;
string filename;
int number;
int number1;
cout << "In order to process, please enter the file name: ";
cin >> filename;
in_file.open(filename.c_str());
if (!in_file.is_open())
{
cout << "Cannot open file" << endl;
}
else
{
in_file >> number;
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
}
system("pause");
return 0;
}
Error in your logic:
in_file >> number; // Assigns 2 from first line to number
if (in_file.fail())
{
cout << "There're no number in the file." << endl;
}
while (in_file >> number >> number1) // Assigns 3 to number from first line
// and assigns 5 to number1 from second line
{
cout << number << " " << number1;
}
You need to use just:
while (in_file >> number >> number1)
{
cout << number << " " << number1;
}
If you must print "There're no number in the file." in the output, you can use:
bool gotSomeNumbers = false;
while (in_file >> number >> number1)
{
cout << number << " " << number1;
gotSomeNumbers = true;
}
if (!gotSomeNumbers)
{
cout << "There're no number in the file." << endl;
}
The method you are using to find to know whether file is empty is not
correct in following way :: As soon as this line gets executed
in_file >> number;
The compiler will treat first line as an integer as a whole , i.e.
number = "2 3" in given scenario. now this is not a standard number
because of space in between 2 and 3 and
in_file.fail() will return true.
The Correct way is to use "eof" function as follows : (I also added
1-2 lines to calculate average of these numbers as you mentioned)
Correct code
Reference :
When will ofstream::open fail?
Checking for an empty file in C++
I recently learned how to read data from a text file, but I would like to continue expanding my knowledge on that matter. I would like to read files that contain numbers and characters. Can anyone give me some advice please?
The following is the code I wrote to read numbers:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream infile("input.txt", ios::in);
if (!infile) {
cout << "Inputxxxxx file could not be opened" << endl;
exit(1);
}
ofstream outfile ("outputt.txt", ios::out);
if (!outfile) {
cout << "inputssss file could not be opened " <<endl;
exit(1);
}
int number;
int answer[10];
for (int i = 0; i < 9 ; i++) {
infile >> number;
answer[i]=number;
cout << answer[i] << " ";
outfile <<answer[i]<< " ";
}
return 0;
}