What do they mean by "Add these integers to sum"? - c++

Write a simple C++ program called sum.ccp, the program should:
1. Read a file that contains several integers.
2. Print these integers on screen.
3. Add these integers together to sum.
4. Print the sum on the screen.
This is what I have so far:
#include <iostream>
#include <fstream>
#include <string>
int main() {
using namespace std;
ifstream inf("sum.ccp");
while (inf) {
std:: string strInput;
inf >> strInput;
cout << strInput << endl;
}
}

Firstly looking at your code, you're already doing some incorrect things.
int main() {
using namespace std;
ifstream inf("sum.ccp");
while (inf) {
std:: string strInput;
inf >> strInput;
cout << strInput << endl;
}
You need to have using namespace std outside of your main method in order to use the majority of basic C++ commands without tacking on std:: to the beginning. So place it underneath all of the "#include" directives.
Secondly, you should make the variable you're using to take in all of the values an integer, and then simply print the number to the screen with a simple cout command.
The hardest part about your assignment here is just taking the numbers from a text file and using them as integers.
Even then, that's pretty easy. Something like this, using ifstream since you're reading from a file.
ifstream inputFile;
inputFile.open(*your file name here, which should be a .txt file.
I think it works w/ .doc files as well,
but just use a .txt file to be safe.)
After that the process is pretty simple. You do use a while loop, but in this case you use the string insertion operator (the double arrows >>), like so:
while(inputFile >> //your number variable)
This lets the text file keep looping your stuff, while also inserting the value into the variable from the start. So from there you can just print it to the screen, tally up the total, and then after the loop you can print the total the screen.
Hope that helps!

Related

How to read file with characters and integers c++

I am 90% done with a homework project of mine but this last step is kicking my butt.
I have a text file that I'm going to be reading from for my program with commands on each line.
Most of the commands are a single letter, but one of them is a letter with an integer behind it.
I ideally need to read the line, if it's just a char go right into a function I've already written for the "Command". If it has a specific character, "F" in this case, I need it to also read the integer that will be separated by a space and pass that into my other function for that command.
Example;
.txt file;
R
L
L
F 20
R
R
For those who are curious I'm mimicking the function of the Logo language that used the little "turtle" to make logo animations for my homework.
Edit
I did try researching some methods to do this but most that I came up with either grabbed just the one char, or involved strings with which I could pull each "line" but then have to read and convert what was in string to separate char and int. If that is truly the "best" way to do it I'll suck it up and do it but I wanted to see if there was something that wasn't initially obvious to me.
This would be my approach:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main() {
ifstream readFromFile("test.txt");
vector<string> fileWords;
string word;
while (readFromFile >> word) {
try {
int number = stoi(word); // here is your number
cout << number << endl;
} catch (const invalid_argument& exception) {
cout << exception.what() << endl; // just for debug
}
fileWords.emplace_back(word);
}
for (const auto& word: fileWords) {
cout << word << ' ';
}
readFromFile.close();
}
It reads word by word, saves it on an array and it also checks if a word is an integer (using the std::stoi function).
Solution by OP.
Resolved Kinda.
I ended up changing my fstream input to;
integer = 0;
char ch;
while(infile >> ch)
if (ch == "F")
{
infile >> integer;
}
// do stuff with code, I used a switch
Then after the switch I put I put integer back to 0.
This pulls the data I needed and stored it in the correct variables.

Getting input from file troubles C++

I've been trying to read some information in from a .txt file in C++ but it's not all working like I expect. Here is some example code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char words[255];
int value = 0;
ifstream input_stream("test.txt");
input_stream >> value;
input_stream.getline(words, 256);
cout << value << endl;
cout << words << endl;
}
And test.txt contains:
1234
WordOne WordTwo
What I expect is for the code to print the two lines contained in the text file, but instead I just get:
1234
I've been reading about getline and istream but can't seem to find any solutions so any help would be appreciated.
Thanks
The newline character remains in the input stream after the read of the integer:
// Always check result to ensure variables correctly assigned a value.
if (input_stream >> value)
{
}
Then, the call to getline() reads the newline character and stops, producing an empty string. To correct, consume the newline character before calling getline() (options include using getline() or ignore()).
Note there is a version std::getline() that accepts a std::string as its argument to avoid using a fixed sized array of char, which is used incorrectly in the posted code.
ifstream's getline method gathers input until one of two options is hit. Either a terminating character or the size passed in is reached. In your case, the newline terminator is encountered before the size is reached.
Use another getline to retrieve the second line of text.
Reference
The problem you are seeing is that the first newline after 1234 is not consumed by input_stream>>(int); so the next getline only reads to the end of that file.
This is a very constructed scenario, commonly found in schoolwork. The more common scenario when reading a textfile is to consider the entire file as linebased text.
In this case the more convenient
string line;
while( std::getline( input_stream, line ) ){
}
is appropriate, and way less error prone.
The textfile would commonly have a predefined format. Perhaps name = value lines, and are parsed as such after the line is read from the file.
Here is a somewhat corrected version of your original code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char words[256]; // was 255
int value = 0;
ifstream input_stream("test.txt");
input_stream >> value;
input_stream.ignore(); // skip '\n'
input_stream.getline(words, 256);
cout << value << endl;
cout << words << endl;
}
Also, I would advise you to use a string instead of a char[] and use the other getline function.

Extracting lines from .txt file, then store words into separate arrays | C++

Our professor gave us this assignment, where we have a .txt file with the following format:
John 23
Mary 56
Kyle 99
Gary 100
...etc. etc.
What we have to do is read the file, and store the names and scores in parallel arrays.
This is turning out to be a bit more challenging to me than I anticipated. What is confusing me, when searching around stack, is all the different libraries people use to do this. Our Prof just wants us to use string, fstream, and sstream to do this.
Below is what I've come up with so far, it compiles perfectly, splits the scores from the names but stores them in the same array:
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int SIZE = 50;
string names[SIZE];
int score [SIZE];
short loop = 0;
string line;
ifstream inFile("winners.txt");
if (inFile.is_open())
{
while(!inFile.eof())
{
istream& getline(inFile >> line);
names[loop] = line;
cout << names[loop] << endl;
loop++;
}
inFile.close();
}
else cout << "Can't open the file" << endl;
return 0;
}
I'm not looking for someone to solve my HW problem, I just want a push in the right direction!
If you want to read two things for each line of input, it seems reasonable to have two "read" statements:
std::string name;
inFile >> name;
int score;
inFile >> score;
std::cout << "Read score " << score << " for name " << name << '\n';
...then you can do that repeatedly until you've read the entire file.
Edit: After you get the basic logic worked out, you might want to think about error handling. For example, what is appropriate behavior for your program if the input file doesn't contain 50 pairs of (name, score)? How can you change your code to get that behavior?
Each line in the file consists of a name and a score separated by whitespace. You're reading each line but not splitting it into its parts (the name and the score).
Ideally you would use a vector for this, but since it seems that you were asked to use arrays we'll stick with arrays. What you have above looks good until you start reading entries. A more idiomatic way to accomplish this is to use std::getline, i.e.
ifstream inFile( "winners.txt" );
std::string line;
while( std::getline( inFile, line )) {
// Do work here.
}
Inside the loop you need to split the line on the space. Without solving the problem for you, I suggest you take a look at the find and substr functions of the string class: here. They will give you everything you need to solve the problem.

C++ dealing with files

I have a problem working in C++ with txt files.. First of all, I want to make a program which
have .cpp and .h files.. which have classes and functions.
So here is my problem:
for example, i have txt file which contains 5 lines of text (players names). So I want to make every line of that txt to be a variable of string.. But as long as I want to use that new variables they suddently disappears.
Here is program code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
int i;
string player[5];
ifstream myfile ("1-Efes Pilsen.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
for (i=0;i<5;i++)
{
getline (myfile,line);
player[i] = line;
}
// after this point I still can use new variables
}
}
else cout << "Unable to open file";
cout << player[1]; // <--- NOT WORKING. WHY?
myfile.close();
}
While it is not clear to me how it's not working, I can guess that there are more contents in the file than just 5 strings (perhaps another newline) which causes the while condition to evaluate to true causing the for loop to read 5 lines (which will fail and not actually read anything) and replace the good values in the string array with crappy ones (empty string).
Instead of having an outer while loop, you probably want to add the condition to the for loop itself; something along the lines of:
for (i=0;i<5 && myfile.good();i++)
{
getline (myfile,line);
player[i] = line;
}

Reading strings and integers from .txt file and printing output as strings only

I'm new to C++, and I'm trying to write a short C++ program that reads lines of
text from a file, with each line containing one integer key and one alphanumeric string value (no embedded whitespace). The number of lines is not known in advance, (i.e., keep reading lines until end of file is reached). The program needs to use the 'std::map' data structure to store integers and strings read from input (and to associate integers with strings). The program then needs to output string values (but not integer values) to standard output, 1 per line, sorted by integer key values (smallest to largest). So, for example, suppose I have a text file called "data.txt" which contains the following three lines:
10 dog
-50 horse
0 cat
-12 zebra
14 walrus
The output should then be:
horse
zebra
cat
dog
walrus
I've pasted below the progress I've made so far on my C++ program:
#include <fstream>
#include <iostream>
#include <map>
using namespace std;
using std::map;
int main ()
{
string name;
signed int value;
ifstream myfile ("data.txt");
while (! myfile.eof() )
{
getline(myfile,name,'\n');
myfile >> value >> name;
cout << name << endl;
}
return 0;
myfile.close();
}
Unfortunately, this produces the following incorrect output:
horse
cat
zebra
walrus
If anyone has any tips, hints, suggestions, etc. on changes and revisions
I need to make to the program to get it to work as needed, can you please
let me know?
Thanks!
See it:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string name;
int value;
ifstream myfile("text.txt", ifstream::in);
while(myfile >> value >> name)
cout << name << endl;
return 0;
}
You are having problems because you attempt to read each line twice: first with getline and then with operator>>.
You haven't actually used std::map in any regard, at all. You need to insert the integer/string pair into the map, and then iterate over it as the output. And there's no need to close() the stream.
Instead of using "! myfile.eof()" use this code it will help.
ifstream is;
string srg;
is.open(filename);
while(getline(is,srg))
{//your code
}