ifstream usage and user input not outputting content to read - c++

I'm practicing ifstream usage. I want the user to enter the file they want to read, in this example num1.txt specifically. I want the console to read one letter from num1.txt and output it on its own line.
I've ran the code below, and after entering "num1.txt" into the console, I get nothing back. I've tried moving around cout << num << endl; to the inner do statement, but it ends up repeating the number 10 an infinite amount.
What am I doing wrong here?
Contents in num1.txt:
2 4 6 8 10
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
int num = 0;
int total = 0;
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
do {
inputFile >> num;
total += num;
}
while(num > 0);
if (total != 0) {
cout << num << endl;
cout << "Total is: " << total << endl;
}
}
else {
cout << "Failed to open file." << endl;
}
inputFile.close();
cout << "Do you want to continue processing files? (yes or no): " << endl;
cin >> cont;
}
while (cont == "yes");
}

Your inner do loop is not correctly validating that operator>> is actually successful before using num. It should be looking at the stream's error state after each read. The easiest way to do that is to change your do loop into a while loop that uses the result of the read as its loop condition, eg:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
string fileName, cont;
ifstream inputFile;
do {
cout << "Please enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if (inputFile.is_open()) {
int num = 0;
int total = 0;
while (inputFile >> num) {
total += num;
}
inputFile.close();
cout << "Total is: " << total << endl;
}
else {
cout << "Failed to open file." << endl;
}
cout << "Do you want to continue processing files? (yes or no): " << endl;
}
while ((cin >> cont) && (cont == "yes"));
return 0;
}

Related

C++ trying to count how many times a user has entered a specific number

I am trying to write a program that counts how many times a specific number is inputted by a user from a while loop. Here is the idea:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
bool progLoop = true;
int Number;
char response;
while (progLoop == true)
{
cout << "Please enter a number: " << endl; \
cin >> Number;
cout << "Number collected!" << endl;
cout << "Number of times that number has been entered: " << endl; //IDK how to do this part which is what I'm looking for.
cout << "Do you want to enter another number?" << endl;
cin >> response;
if (response == 'y')
{
progLoop == true;
}
else if(response == 'n')
{
progLoop == false;
}
}
}
I'm looking for a way that I can store a sort of value of how many times that specific number has been entered into the program. Would like to clarify if there are any questions! Thanks! (Modifying my code would be great!)
Use a hashmap:
#include <unordered_map>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
int number;
char response = 'y';
unordered_map<int, int> m; // your hashmap
while (response == 'y')
{
cout << "Please enter a number: " << endl;
cin >> number;
cout << "Number collected!" << endl;
cout << "Number of times that number has been entered: " << ++m[number] << endl; // preincrement your hashmap at key number
cout << "Do you want to enter another number? (y/n)" << endl;
cin >> response;
response = tolower(response); // give a chance to exit the loop if your user like to use caplock (like Trump)
}
}
Expanding my comment into an answer
One way of doing this is to use an std::vector and every time a new number is inputted, it is pushed back into the vector. Then you can std::count that number when you need to check. In your program, it would look something like this:
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
using std::cout;
using std::cin;
using std::endl;
int main() {
bool progLoop = true;
int Number;
std::vector<int> numCount;
char response;
while (progLoop == true)
{
cout << "Please enter a number: " << endl;
cin >> Number;
numCount.push_back(Number);
cout << "Number collected!" << endl;
cout << "Number of times that number has been entered: " << std::count(numCount.begin(), numCount.end(), Number) << endl;
cout << "Do you want to enter another number?" << endl;
cin >> response;
if (response == 'y')
{
progLoop = true; // You accidentally used == here
}
else if(response == 'n')
{
progLoop = false; // You accidentally used == here
}
}
}

cin as a function argument

I have a question in this code. What does fucntion receive when we use cin as a argument.
For example cin stops when he finds a white space or '\n', so if the input is "1 2 3 4 5" the program will return 5 but I can't understand why.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
double max_value(istream& in) // can be called with 'infile' or 'cin'
{
double highest;
double next;
if (in >> next)
highest = next;
else
return 0;
while (in >> next)
{
if (next > highest)
highest = next;
}
return highest;
}
int main()
{
double max;
string input; cout << "Do you want to read from a file? (y/n) ";
cin >> input;
if (input == "y")
{
string filename;
cout << "Please enter the data file name: ";
cin >> filename;
ifstream infile; infile.open(filename);
if (infile.fail())
{
cerr << "Error opening " << filename << "\n";
return 1;
}
max = max_value(infile);
infile.close();
}
else
{
cout << "Insert the numbers. End with CTRL-Z." << endl; max = max_value(cin);
}
cout << "The maximum value is " << max << "\n";
return 0;
}

c++ how to display the string searching key word with its exact line number?

I have a programmer for c++ that ask me a file name first, then ask for the search word. the line that contains it should be displayed with its exact line number in front.
for example:
20:XXXXXX.
I have code here. I don't know how to display the line number. please help me.
#include <iostream>
#include <string> //to work with strings
#include <fstream>
using namespace std;
int main()
{
int occurenceNumber = 0;
int counter = 0;
int lineNum;
string fileName;
string toSearch;
string lineRead;
ifstream inputFile;
cout << "Enter the file name: ";
cin >> fileName;
inputFile.open(fileName);
if(!inputFile){
cout << "Error opening file, or file doesn't exist!";
cout << "Try again!\n";
return 0;
}
cout << "Enter string to search for: ";
cin >> toSearch;
cin.ignore();
while(getline(inputFile, lineRead))
{
if(lineRead.find(toSearch, 0) < lineRead.length())
{
occurenceNumber++;
cout << lineRead << endl;
}
}
cout << toSearch << " was found " << occurenceNumber;
cout << " times. \n";
inputFile.close();
return 0;
}
You set a counter variable. You just forgot to use it. This is the while loop in your code with that counter variable that you defined but forgot to use.
If you place the counter++ at the beginning of that while loop, the first line is line 1. On the other hand, if you place it at the end of the loop, the first line is line 0.
while(getline(inputFile, lineRead))
{
counter++;
if(lineRead.find(toSearch, 0) < lineRead.length())
{
occurenceNumber++;
cout << counter << ":" << lineRead << endl;
}
}

Unable to successfully compare strings

The idea is to take a file and print out the amount of words in the file. Then prompt the user to enter a word, the program will then count how many times that word is iterated. However I am having trouble with being able to pick out the chosen word from the file, no matter what it still returns 0.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream infile;
int i = 0;
string word_counter;
string file_name;
bool opened = false;
while (opened == false){
cout << "Enter the name of the file to read: ";
cin >> file_name;
infile.open(file_name, fstream::in);
opened = true;
if (!infile.is_open()) {
cout << "ERROR: CANNOT OPEN INPUT FILE" << endl;
cout << endl;
opened = false;
}
}
while (!infile.eof()){
infile >> word_counter;
cout << word_counter << endl;
i++;
}
cout << "Read in " << i << " words\n";
bool done = false;
while (!done){
string word;
string quit;
int x = 0;
cout << "Enter a word to count how many times it occurs: ";
cin >> word;
while (!infile.eof()){
infile << word_counter;
if (word_counter == word){
x++;
}
}
cout << "The word \"" << word << "\" occurs " << x << " times" << endl;
cout << "Press any key to continue, or press Q to quit: ";
cin >> quit;
if (quit == "q" || quit == "Q"){
done = true;
}
}
infile.close();
return 0;
}
You forgot to rewind the file.
Add the following lines
infile.clear(); // Clear the EOF flag
infile.seekg(0); // rewind
right after
cin >> word;
Also, you are using << instead of >> in the line
infile << word_counter;
Since you are not reading anything from the file, the enclosing while block stays in an infinite loop. Change that line to:
infile >> word_counter;

extract cin data to a variable that fits

In case of an invalid input, I want extract the invalid input from cin and store it in a variable that fits. How can I do that?
#include<iostream>
using namespace std;
int main(){
int number;
cout << "Enter a number: " << endl;
cin >> number;
if(cin.fail()){
cout << "Error!" << endl;
//HOW CAN I STORE THE INVALID INPUT WHICH IS STORED IN cin INTO A STRING?
}
return 0;
}
When you detect that failbit is set, reset it, and use std::getline to read entire line of invalid input into std::string from std::cin:
#include <iostream>
#include <string>
int main()
{
int number;
while(true)
{
std::cout << "Enter a number (0 to exit): " << std::endl;
std::cin >> number;
if(std::cin.fail())
{
std::string error_data;
std::cin.clear(std::cin.rdstate() & ~std::ios::failbit);
std::getline(std::cin, error_data);
std::cout << "You didn't enter a number - you've entered: " << error_data << std::endl;
}
else
{
std::cout << "Number is: " << number << std::endl;
if(number == 0)
{
break;
}
}
}
return 0;
}