How to properly read an input file in C++? - c++

I'm relatively new to C++ so please excuse the use of namespace std. I'm trying to read a numeric value from a file, and determine its prime factors. Despite not failing it will ignore input, displaying an endless loop of '0' and '2is a prime number'. Below is both my code and text file.
Code:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
int div = 0, num = 0, count = 0;
string inputFile;
ifstream fin;
cout << "Enter input file name: ";
getline(cin, inputFile);
fin.open(inputFile.c_str());
if (fin.fail())
{
cout << "Bad file.\n";
cin.ignore();
getchar();
exit(0);
}
fin >> num;
cout << left << setw(12) << "Number" << setw(15) << "Prime Factors\n"
<< "---------------------------\n"
<< setw(12) << num << endl;
while (!fin.eof())
{
div = 2;
count++;
cout << setw(15) << num;
if (num < 0)
cout << "Can't do negative numbers\n"
else
{
cout << div;
while (div <= num / 2)
{
if (num % div == 0)
{
num = num / div;
cout << div;
}
else
div++;
}
}
if (div >= num / 2)
cout << "is a prime number\n";
fin.ignore(10, '\n');
fin >> num;
cout << setw(12) << num << endl;
}
if (count == 0)
cout << "No data was processed, data file is empty.\n";
cin.ignore(10, '\n');
getchar();
return (0);
}
Input.txt (Ended with a singular blank line for EoF):
348
23

Related

C++ program not able to open files from user input

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main() {
ifstream inputFile;
string fileName;
int value = 0;
int numOfNumbers = 0;
int oddNumbers = 0;
int evenNumbers = 0;
double sum = 0.0;
double average = 0.0;
int counter = 0;
//Ask user for file name
cout << "Enter file name to read: " << endl;
cin >> fileName;
//Open file
inputFile.open(fileName);
//Calculate information
if (inputFile.is_open())
{
while (inputFile >> value)
{
numOfNumbers++;
sum += value;
}
}
else
{
//Display error if file doesn't open
cout << "Error reading file." << endl;
}
if (numOfNumbers > 0)
average = sum / numOfNumbers;
else
average = 0.0;
if (numOfNumbers > 0)
{
while (inputFile >> value)
{
counter++;
if (value % 2 == 0)
evenNumbers++;
else
oddNumbers++;
}
cout << "Number of numbers = " << numOfNumbers << endl;
cout << "Average = " << average << endl;
cout << "Sum = " << sum << endl;
cout << "Number of even numbers: " << evenNumbers << endl;
cout << "Number of odd numbers: " << oddNumbers << endl;
}
else
cout << "Cannot compute values." << endl;
inputFile.close();
return 0;
}
I cannot get this program to open my file nor read the contents to do these calculations. I have moved the file into the directory and have tried typing the name with the extension (.txt). I also removed the quotations I previously had placed around fileName in inputFile.open(fileName);
Any recommendations?

incorrect c++ output when executing

I am trying to replicate the following program but without including the cout function, this is the program with the cout function:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
bool incorrect = 1;
int temp;
int i = 0;
int peopleInGroup = 1;
string x = "";
int max;
stringstream ss;
cout << "Input the number of people in a group: 2 to ";
getline (cin, x);
ss << x;
ss >> max;
while(incorrect == 1)
{
i++;
cout << "Testing: " << i << endl;
peopleInGroup = 1;
while(peopleInGroup < max)
{
peopleInGroup++;
cout << "Remainder of (" << i << " /" << peopleInGroup << ") =" << (i % peopleInGroup) << " =" << (peopleInGroup - 1) << " ";
if((i % peopleInGroup) == (peopleInGroup - 1))
{
cout << "TRUE" << endl;
if(peopleInGroup == max)
{
incorrect = 0;
break;
}
else{}
}
else
{
cout << "FALSE" << endl;
break;
}
}
}
if(incorrect == 0)
{
cout << endl << "The answer is " << i;
}
else
{
cout << endl << "Unable to find the answer";
}
cin >> temp;
}
which when run shows
Input the number of people in a group: 2 to
and when I type 3, it comes out with 5 which is correct:
Input the number of people in a group: 2 to 3
...
The answer is 5
without cout, however when I do this the program comes out with an incorrect answer:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
bool incorrect = 1;
int temp;
int i = 0;
int peopleInGroup = 1;
string x = "";
int max;
stringstream ss;
cout << "Input the number of people in a group: 2 to ";
getline (cin, x);
ss << x;
ss >> max;
while(incorrect == 1)
{
i++;
peopleInGroup = 1;
while(peopleInGroup < max)
{
peopleInGroup++;
if((i % peopleInGroup) == (peopleInGroup - 1))
{
if(peopleInGroup == max)
{
incorrect = 0;
}
}
}
}
if(incorrect == 0)
{
cout << endl << "The answer is " << i;
}
else
{
cout << endl << "Unable to find the answer";
}
cin >> temp;
}
which is always
max - 1
for example, if I put in 3, it comes out with 2
you miss the break statement in the following code.
cout is not necessary but the break statement is to come out from the execution block. If you put the break statement as given in above code you will get the desired output

How do I check if the input is letter?

I'm trying to display "invalid option" when the user enters a letter instead of a number. I tried using the isalpha() function but I get an infinite loop showing 0 Invalid option!try again:. The 0 from the output is displayed when entering a letter. When I actually type in the number 0 the message is displayed and the loop is exited.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
cout << "Guess a number 1-100: ";
cin >> userInput;
cout << endl;
if(userInput == answer) {
cout << "Correct!\n\n";
}
while(userInput != answer) {
if(userInput < 1 || userInput > 100 || isalpha(userInput)) {
cout << userInput << " Invalid option!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
cin >> userInput;
cout << endl;
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
cin >> userInput;
cout << endl;
}
}
cout << userInput << " is correct!\n\n";
return 0;
}
When you need to deal with user input differently based on some logic, your best option is to:
Read lines of text. Figure out what to do when there is no more input.
Process each line of text using custom logic.
In your case, you could use:
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cctype>
using namespace std;
int main() {
// Vaules do not change
const int minNum = 1;
const int maxNum = 100;
int userInput;
// Changes every second
srand(time(0));
// Random number is stored
const int answer = minNum + (rand() % maxNum);
cout << answer << endl; // For testing purposes
std::string line;
cout << "Guess a number 1-100: ";
while ( getline(std:::cout, line ) )
{
// Deal with empty lines.
if ( line.size() == 0 )
{
continue;
}
// If the first character is a letter ...
if(isalpha(line[0])) {
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
// Extract the number from the line using a stringstream.
// If there is a problem extracting the number ...
std::istringstream str(line);
if ( !(str >> userInput ) )
{
cout << line << "\n Invalid option!\ntry again: ";
continue;
}
cout << endl;
// Check the user input against the random answer.
if(userInput == answer) {
cout << "Correct!\n\n";
}
else if(userInput < 1 || userInput > 100 ) {
cout << userInput << " Invalid option!\ntry again: ";
}
else if(userInput < answer) {
cout << userInput << " is too low!\ntry again: ";
}
else if(userInput > answer) {
cout << userInput << " is too high!\ntry again: ";
}
cout << "Guess a number 1-100: ";
}
cout << userInput << " is correct!\n\n";
return 0;
}

having trouble outputting what i wrote to a file

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream fout1;
ofstream fout2;
string fnameOdd;
string fnameEven;
int x;
int numEven(0);
int numOdd(0);
cout << "Enter name of file for odd integers: ";
getline(cin, fnameOdd);
fout1.open(fnameOdd.c_str(), ios::out);
cout << "Enter name of file for even integers: ";
getline(cin, fnameEven);
fout2.open(fnameEven.c_str(), ios::out);
if(!fout1.is_open())
{
cerr << "Unable to open file" << fnameOdd << endl;
exit(10);
}
if(!fout2.is_open())
{
cerr << "Unable to open file" << fnameEven << endl;
exit(15);
}
cout << "Enter list of odd and even integers (followed by 0): " << endl;
cin >> x;
while (x != 0)
{
if (x % 2 == 0)
{
numEven++;
}
else
{
numOdd++;
}
}
fout1 << numEven;
fout2 << numOdd;
cout << "File " << fnameOdd << " contains " << numOdd << " odd integers. " <<endl;
cout << "File " << fnameEven << " contains " << numEven << " even integers. " <<endl;
fout1.close();
fout2.close();
return 0;
}
I am having trouble outputting anything to the screen, nothing is happening it is just inputting the file names and integers. i am not sure how to output what i have wrote onto the file, and reading my book does not help.
You forget that your input statement cin >> x; needs to go inside the loop as well
cin >> x;
while (x != 0)
{
if (x % 2 == 0)
{
numEven++;
}
else
{
numOdd++;
}
cin >> x; // new line here
}
The way you wrote it after you input the first value for x, it never changes it's value again. So the while loop never ends. That's why you didn't see any output.

Making my do while loop neater by removing repeating code

Hi here is my question.
Write a program that uses a do-while statement. It reads in an integer
n from the keyboard. If n is not in the range 1 to 10 it makes an audible
“beep” and asks for another integer. If n is in the correct range, it writes
out “You have input n” and then exits.
Here is my answer.
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
do
{
cout << "Enter an integer." << endl;
cin >> number;
if (!(number >= 1 && number <= 10))
{
Beep(400, 400);
}
}
while (!(number >= 1 && number <= 10));
cout << "You have input " << number << endl;
system("PAUSE");
}
You can see the line
(!(number >= 1 && number <= 10))
is repeated. Is there any workaround for this?
int GetNumber()
{
int number;
cout << "Enter an integer." << endl;
cin >> number;
return number;
}
void main()
{
int n = GetNumber();
while(n < 1 || n > 10)
{
Beep(400, 400);
n = GetNumber();
}
cout << "You have input " << n << endl;
system("PAUSE");
}
#include <iostream>
#include <Windows.h>
using namespace std;
void main()
{
int number = 0;
bool invalid_input = true;
do
{
cout << "Enter an integer." << endl;
cin >> number;
invalid_input = !(number >= 1 && number <= 10);
if (invalid_input)
{
Beep(400, 400);
}
}
while (invalid_input);
cout << "You have input " << number << endl;
system("PAUSE");
}
Perhaps...
int number = 0;
while (true)
{
cout << "Enter an integer." << endl;
if (cin >> number && number >= 1 && number <= 10)
break;
Beep(400, 400);
}
cout << "You have input " << number << endl;
system("PAUSE");