Having just finished my first teach yourself C++ book, I’m now trying to have some fun creating. I’m still trying to get my head around some functions however.
Could anyone help me out with what the code would be for these three actions.
First code :
Open txt file named "inputs.txt"
If first line is 1, run an application from the same folder.
If it is 0 do nothing
Second code :
Open txt file named "inputs.txt"
If second line's number there is greater than 50, run application 1
If second line's number is less than 50, run application 2
Third code :
Open txt file named "inputs.txt"
If third line has something written there, write what it is to third line of "outputs.txt"
ifstream ifs("inputs.txt"); //Open txt file named "inputs.txt"
ifs >> int_var;
if (ifs.good() && int_var == 1) //If first line is 1,
{
//run an application from the same folder.
}
1 2 3 4 5 6 7 8 9 10 11 12 13
ifstream ifs("inputs.txt"); //Open txt file named "inputs.txt"
ifs. ignore(1000, '\n'); //skip first line
ifs >> number;
if (ifs.good() && number > 50) //number there is greater than 50
{
//run application 1
}
else //If second line's number is less than 50
{
// run application 2
}
You should be able to figure out the third one from these examples.
Note that I use ifstream.good() to check if the character read was indeed a number and that the file was opened successfully.
You will need to add a few things, like declarations for the int_var and number variables.
Hopefully that gets you on your way at least.
Do let us know if you need any further help.
Yes! That actually makes it very clear to me. Thank you.
Although I'm fairly new to C++, I have a decent amount of experience moddling PC games and I've used things similar to that.
One last question on this which is more for my curiosity : Numbers transfer fine between the txt files, but words or letters always appear in output.txt as a number sequence I don't understand. Why is that, and if I wanted to transfer words what would I have to do?
You are presumably reading the input from the user into an integer variable.
Integers cannot hold text, only numbers, so I think what's happening is that the ASCII values1 of the characters are assigned to the integer variable.
If you want to read in characters, easiest way is to use std::string: