meet error while trying to read int number from input file - c++

I am new to coding C++. I meet issue while trying to read 2 int number from input file, calculate them and then export to output. System showing issue at line 14,18 and 21 of the loop. Please give me advice on this. Thanks all!
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream file;
file.open("input.txt");
string word;
word.clear();
int a, b;
int count = 0;
while(file>>word)
{
count++;
if (count % 2 == 1){
a = stoi(word);
}
else {
b = stoi(word);
}
}
int TOTAL = a + b;
int Difference = a - b;
int Multiply = a * b;
int Division = a / b;
int MUD = a % b;
ofstream out("output.txt");
out << "Input Values: " << a << " " << b << endl;
out << "Sum of two numbers: " << TOTAL << endl;
out << "Difference of two numbers: " << Difference << endl;
out << "Multiply of two numbers: " << Multiply << endl;
out << "Division of two numbers: " << Division << endl;
out << "Modular division of two numbers: " << MUD << endl;
cout << "Calculation written in file" << endl;
out.close();
return 0;
}

#include <string> because you are using string functions that's the problem I think

Related

C++ random srand code-if else does not give correct result

I am not receiving correct response to my code. It should give 'Excellent' when I type in correct number; however, it always outputs 'Incorrect' - Please suggest.
#include <iostream>
#include <ctime>
using namespace std;
int guess()
{
int x = 0;
x = 1 + rand() % 1000;
return x;
}
int main()
{
int input = 0;
srand( time( 0 ) );
cout << guess() << endl;
cout << "I have a number between 1 and 1000. " << endl;
cout << "Can you guess my number? " << endl;
cout << "Please type your first guess. " << endl;
cin >> input;
if (guess() == input)
cout << "Excellent! You guessed the number! " << endl;
else
cout << "Incorrect! " << endl;
system ("pause");
return 0;
}
You are calling twice the function guess(), so it will give you probably different values at each run. You must store the value and then compare it with the original one.

Fixing this simple code

I'm a beginner at coding and I can't fix this code and I'm going crazy. It keeps telling me certain variables were not declared and i'm not sure how to fix it.
#include <iostream>
using namespace std;
int main()
{
int (a = 0), sum;{
cout << "This program should read all integer numbers ";
cout << "to sum until a negative number is entered\n";
exit(0);
}
while(a < 0) {
cout << "Enter an integer number: ";
cin >> a;
sum += a;
}
cout << "The sum is sum\n";
return 0;
}
You did not initialize sum, so it could start with any value.
You have extra layers of pointless { } around for no reason.
Your final cout statement does not actually print the varaible.
Change it to: cout << "The sum is " << sum << "\n";
#include <iostream>
using namespace std;
int main()
{
int a = 0, sum = 0;
cout << "This program should read all integer numbers ";
cout << "to sum until a negative number is entered\n";
do {
cout << "Enter an integer number: ";
cin >> a;
if (a > 0)
{
sum += a;
cout << "The sum is currently: " << sum << "; but this is not yet the final value.\n";
}
} while(a > 0) ;
cout << "The sum is " << sum << "\n";
return 0;
}
Lots of gotchas with your code.
Issues I found and corrected:
You have extra parentheses and curly brackets.
You didn't initialize the variable called sum
You initialize the variable called a to 0 but your loop will only execute while a is less than 0
I had to #include "stdafx.h" above where you included iostream
The line that says "The sum is sum" - the second sum should be outside the double quotes so that it will be treated as a variable rather than text.
This code works, please compare it to yours:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int a = 0, sum = 0;
cout << "This program should read all integer numbers ";
cout << "to sum until a negative number is entered\n";
while (a <= 0) {
cout << "Enter an integer number: ";
cin >> a;
sum += a;
}
cout << "The sum is " << sum << "\n";
return 0;
}

Printing multiple outputs on same line

there. I'm self learning C++ out of "C++ without fear". There is an exercise dealing with the GCD of 2 numbers that asks to print "GCD(a,b) =>" at each step in the proceedure. I was able to get this working:
int gcd (int a, int b);
int main() {
int i,j;
cout << "Enter the first integer" << endl;
cin >> i;
cout << "Enter the second integer" << endl;
cin >> j;
int k = gcd(i,j);
cout << "The GCD is " << k << endl;
system("PAUSE");
return 0;
}
int gcd (int a, int b){
if(b==0){
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " <<endl;
return a;
}
else {
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
return gcd(b,a%b);
}
}
I was just wondering if there is a nicer way to go about printing each step of finding the GCD. That is, is there a "nicer" way to write this part of the code:
cout << "GCF(" << a;
cout << "," << b;
cout << ") => " << endl;
? Thanks in advance.
You can do something like:
cout << "GCF(" << a << ',' << b << ") =>" << endl;
It is not C++ but you could use the C way of printing it which in my opinion looks better in this situation because there are far fewer stream operators, << in the way.
#include <cstdio>
printf("GCF(%d, %d) =>\n", a, b);
But this is a C way of doing things... You could use something like boost::format as is mentioned in this SO answer.
try this one
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
cout << 6+2 <<"\n" << 6-2;
}

file setprecision c++ code

I had this code in C++ that is working just fine, first it ask the user for a
file name, and then saves some number in that file.
But what I am trying to do is to save numbers with two decimal places, e.g the
user types 2 and I want to save the number 2, but with two decimal places
2.00.
Any ideas of how to do that?
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
double num;
double data;
string fileName = " ";
cout << "File name: " << endl;
getline(cin, fileName);
cout << "How many numbers do you want to insert? ";
cin >> num;
for (int i = 1; i <= num; i++) {
ofstream myfile;
myfile.open(fileName.c_str(), ios::app);
cout << "Num " << i << ": ";
cin >> data;
myfile << data << setprecision(3) << endl;
myfile.close();
}
return 0;
}
Ok, you need to use setprecision before the data is written.
I would also move the open and close of the file out of the loop (and the declaration of myfile, of course, as it's generally a fairly "heavy" operation to open and close a file inside a loop like this.
Here's a little demo that works:
#include <iostream>
#include <fstream>
#include <iomanip>
int main()
{
std::ofstream f("a.txt", std::ios::app);
double d = 3.1415926;
f << "Test 1 " << std::setprecision(5) << d << std::endl;
f << "Test 2 " << d << std::endl;
f << std::setprecision(7);
f << "Test 3 " << d << std::endl;
f.precision(3);
f << "Test 3 " << d << std::endl;
f.close();
}
Note however that if your number is for example 3.0, then you also need std::fixed. E.g. if we do this:
f << "Test 1 " << std::fixed << std::setprecision(5) << d << std::endl;
it will show 3.00000

C++ - program has stopped working

The code that I posted below is supposed to work in recursion (the Sort() function) even up to 1kk times. The problem is: when the Sort() function gets into loop number 43385 the console stops working and alerts: "The program has stopped working". Is it a problem with memory? If yes, where is the bad part of the code? Greetings.
#include <iostream>
#include <string>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
if(i==n-1)
return counter;
else
Sort(i+1);
}
int main()
{
cin >> n >> a >> b;
Sort(0);
return 0;
}
Perhaps a call stack overflow because of too deep recursion?
To add to iltal's comment, you may want to print out information on strings a, b: a.size(), a.length(), a.capacity(), a.max_size()
I'm not sure what this code is trying to do. Here's a revision, with some print statements added, along with a random string generator.
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
string a, b;
int n=0,i=0,counter=0;
int Sort(int i)
{
int x=0,y=0,tmp0=0;
char tmp1;
for(x=i;x<n;x++) {
if(a[x]==b[i]){
tmp0=x;
tmp1=a[x];
cout << "x = " << x << " set tmp0 to " << tmp0 << " and tmp1 to " << tmp1 << endl;
break;
}
else
continue;
}
for(y=tmp0;y>=i;y--)
y==i ? a[i]=tmp1 : a[y]=a[y-1];
counter+=tmp0-i;
cout << " endof sort: a is " << a << endl;
cout << " b is " << b << endl;
if(i==n-1) {
cout << "Returning counter " << counter << endl;
return counter;
} else {
cout << "Running sort(" << i << " + 1)" << endl;
Sort(i+1);
}
}
string randomStrGen(int length) {
static string charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
string result;
result.resize(length);
for (int i = 0; i < length; i++)
result[i] = charset[rand() % charset.length()];
return result;
}
int main()
{
n = 50;
srand(time(NULL));
string a0, b0;
a0 = randomStrGen(n);
a = a0;
b0 = randomStrGen(n);
b = b0;
// cin >> n >> a >> b;
cout << "Max string size is " << a.max_size() << endl;
cout << "Calling sort" << endl
<< " n is " << n << endl
<< " a is " << a << endl
<< " b is " << b << endl;
Sort(0);
cout << " endof program: a inital: " << a0 << endl;
cout << " a final: " << a << endl;
cout << " b inital: " << b0 << endl;
cout << " b final: " << b << endl;
return 0;
}
counter is of type int but it has a lot of values summed in it which may be in all larger than int. maybe try int64?
You could hard code some test cases, like n = 20, a = "xyz...", b = "abc...", and add print statements to your sort function to track what is going on. Also, it may be helpful to add some comments to clarify what the purpose of the different loops are.