Printing integers from a file using an array - c++

I'm just beginning to learn C++ and I am having some trouble with a program. It's supposed to sort numbers from an external file. I've managed to successfully code the sorting algorithm, but I am having trouble working with the external file. I am just testing some things out in a separate program to gain an understanding of how things like ifstream work. I should be able to figure out how to implement it into my program once I gain a better understanding of how it works.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
using namespace std;
int count;
ifstream InFile;
InFile.open ("unsorted.txt");
InFile >> count;
int numbers[count];
for(int a = 0; a < count; a++)
InFile >> numbers[a];
cout << numbers << endl;
}
Currently, the output for this is 0x7ffc246c98e0 I am not sure why this is the case I'm just attempting to print my file of integers. Could anyone help explain what I am doing wrong? I'd be very thankful.

When you do
cout << numbers << endl;
you print the pointer to the first element of the array.
You want
cout << numbers[a] << '\n';
to print the current element.
Furthermore, if that's all your program is doing, then you don't actually need the array. All you need is a single int variable:
int value;
for (int a = 0; a < count; ++a)
{
InFile >> value;
cout << value << '\n';
}
That also solve the problem with the variable-length array (since there isn't any).

If you intend to use count variable to count the file size or something, it is where your code goes wrong. You can't count the length of the file as like as you are trying.
while( getline ( InFile, line ) )
{
count += line.length();
}
Maybe, try like this!!!
If you use
InFile>>count;
it would try to store all the string from InFile stream to count, which is not intended.

Related

Eof in case of cin and istringstream [duplicate]

I've tried a bunch of methods listed on here but none of them work. It's always waiting for more input.
I've tried while(std::getline(std::cin, line)) and the method below, nothing seems to work:
#include <iostream>
#include <sstream>
using namespace std;
int main(){
long length = 1UL<<32;
int array[length];
// memset(array, 0, (length-1) * sizeof(int));
for(int i = 0; i < length; i++)
array[i] = 0;
string line;
int num;
while(!cin.eof()){
getline(cin,line);
stringstream ss(line);
ss >>num;
array[num]++;
}
for(int i = 0; i < length; i++)
if(array[i]){
cout << i << ": ";
cout << array[i] << endl;
}
}
First off, do not use std::cin.eof() to control your loop! It doesn't work. Also, you always need to check for successful input after the input.
That said, to terminate the input you'll need to enter the appropriate end of file character, probably at the start of the line (how it works entirely somewhat depends on the system, some settings, etc.). On Windows you'd use Ctrl-Z, on UNIXes you'd use Ctrl-D.
First off, this part of your program attempts to allocate 4 GB of memory on the stack, which doesn't work on my machine (good luck finding any machine with 4 GB of continuous memory space):
long length = 1UL<<32;
int array[length];
If I change that to a much more reasonable:
long length = 32;
Then it works fine for me:
$ g++ -g test.cpp -o test && ./test
2
5
# pressed control+d
2: 1
5: 2
$
So I'm guessing something else is wrong.
Note: Unless you actually plan to use all of those indexes, you may want to considering using an unordered_map, so you only use the space you actually need.
The condition you are looking for can be most easily tested by evaluating "std::cin" as a bool, i.e. while (cin). But it won't do this until you have tried to read beyond EOF, so expect an empty getline:
#include <iostream>
#include <string>
int main() {
std::string input;
while (std::cin) {
std::cout << "Type something in:\n";
std::getline(std::cin, input);
if(input.empty())
continue;
std::cout << "You typed [" << input << "]\n";
}
std::cout << "Our work here is done.\n";
return 0;
}
Live demo: http://ideone.com/QR9fpM

trying to read data file, store in array and print all the elements but it isnt working

not sure what i'm doing wrong but this is my code
int main (){
int marks [100];
int i=0;
ifstream inputfile;
ofstream outputfile;
inputfile.open("data.txt");
if(!inputfile.is_open())
{
cout<< "File did not open"<< endl;
return 0;
}
cout<<"Marks in File:"<<endl;
while (marks [i] != -1)
{
inputfile>>marks[i];
cout << marks[i] <<endl;
i++;
}
return 0;
}
the output is messed up and returns stuff that was never in the data file to begin with
Here is the minimal code for reading data from a file and write it to console. Description is added as comments
#include <fstream>
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream configrecord("D:\\Temp\\temp.txt"); // opening the file named temp for reading.
if(configrecord.good()) // check whether the file is opened properly.
{
string line;
while (getline(configrecord, line)) // reading a line from file to std::string
{
cout << line; // printing the line, if you want it to store in an array, you can use the std::string::data() api to get the character pointer.
}
configrecord.close(); // closing the file after reading completed
}
}
If we translate your code to English, we get:
Check if the current array element is -1, if it is, break the loop.
Read the value into the current array element.
Output the value.
Move to the next array element and repeat.
Notice a big problem: We're checking if the value is -1 before we actually read it. We need to reverse the order of steps 1 and 2 so that we get:
Read the value into the current array element.
Check if the current array element is -1, if it is, break the loop.
Output the value.
Move to the next array element and repeat.
We can do this by using true as our loop condition and then using an if statement to check if the inputted value is -1 later in the loop, using break to break the loop if it is.
#include <fstream>
#include <iostream>
//using namespace std; is considered bad practice
int main()
{
std::ifstream inFile("input.txt");
int marks[100];
//check if file is open stuff...
for(int i = 0; true; i++)
{
inFile >> marks[i];
if(marks[i] == -1) break;
std::cout << marks[i] << '\n'; //endl flushes the buffer, unnecessary here.
}
}
Of Note: it is good practice that if you use an if statement, you also include an else statement. Also, your while loop is confusing, because it stops if it encounters negative one, so I am assuming you know that integer -1 is not in the file.
int n = -1;
if(!inputfile.is_open())
{
cout<< "File did not open"<< endl;
}
else
{
cout<<"Marks in File:"<< endl;
while(!inputfile.eof()){ // .eof is bad practice, but for this instance it works.
File >> marks[n];
n++; // Essentially the size of the array (Number of values), keeping track of how many values there are will assist you in the output process.
}
}
When you are done reading the file, you should close it and then use the data in the array.
inputfile.close();
Lastly, in order to output an array of data, you must use a for loop or some type of iterator to access the values stored in the array.
for(int i=0; i < n ; i++) // Output array. Where array size is less than n.
{
cout << marks[i] << " "; // " " inputs a space in between each word.
}

Why is the next line not executing C++

I have attached my full source code of my program that can open a .txt file. It doesn't execute after the cout << length. I am trying to store the .txt file information in memory by using an array.
#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
char filename[128];
char file[10][250];
int count;
int length;
string line;
int main ()
{
int count = 0;
int length = 0;
cout << "Filename: ";
cin.clear();
cin.getline(filename, sizeof(filename));
string new_inputfile(filename);
ifstream inputfiles (new_inputfile.c_str());
if(!inputfiles.is_open())
{
cout << "File could not be opened. \n ";
}
else
{
for (int i=0; getline(inputfiles,line); i++)
{
length++;
}
cout << length;
// char file[length][250]; <- How can I create the array based on the length variable?
// CODE DOES NOT EXECUTE AFTER THIS.
while(!inputfiles.eof() && (count<10))
{
inputfiles.getline(file[count],250);
count++;
}
for(int i=0; i < count; i++)
{
cout << file[i] << endl;
}
}
inputfiles.close();
return 0;
}
Also, since file[] is char, say for example file[1] contained the char Name=Mike, how do I strip off everything before the =. I want just Mike. I know with string, I can use substr() method, but I don't know for char.
This is horribly wasteful way to count number of lines in a file.
for (int i=0; getline(inputfiles,line); i++) // i is also completely useless here
{
length++;
}
You're reading the whole file only to throw everything away and start again! And after this loop is done, inputfiles.eof() will be true and you'll never enter neither the next while loop nor the last for loop (because i == count). Execution skips directly to inputfiles.close() and then you return from main.
I suggest you work on the line string as you go:
for ( ; getline(inputfiles, line); )
{
// do stuff with line and ditch the global char arrays
}
If you want store the lines for later, well, just save them :) The easiest thing to do is to use a vector:
std::vector<std::string> all_them_lines;
while (getline(file, line) all_them_lines.emplace_back(line);
There, the entire file is now saved in all_them_lines, line by line. You can access them just like you would in an array, like all_them_lines[0]. You also don't need to know the number of lines beforehand - vectors expand automatically when you add stuff to them.
Now to parse a line and extract formatted input from it, check out what stringstream class has to offer.
You asked:
// char file[length][250]; <- How can I create the array based on the length variable?
Declare file as:
char (*file)[250] = NULL;
and then,
file = new char[length][250];
Make sure you call delete [] file before the end of the function.
You said:
// CODE DOES NOT EXECUTE AFTER THIS.
You can rewind the stream and start reading from it again.
inputfiles.seekg(0);
count = 0;
while(!inputfiles.eof())
{
inputfiles.getline(file[count],250);
count++;
}

Why is this file not reading into my array?

Can anyone tell me why my array is not filling up with the info I am trying to get from my data file? When I output the array it just gives me garbage. Thanks in advance.
#include <iostream>
#include <fstream>
using namespace std;
// function main begins program execution
int main()
{
/* input correct answers file */
const int ARRAY_SIZE = 20; // Array size
int correctAnswers[ARRAY_SIZE]; // Array to hold correct answers
int count = 0; // Loop counter variable
ifstream inputFile; // Input file stream object
// open the file
inputFile.open("c:\\correctanswers.txt");
// read the numbers from the file into the array
while (count < ARRAY_SIZE)
{
inputFile >> correctAnswers[count];
count++;
}
// close the file
inputFile.close();
// display the correct answers
cout << "The correct answers are: ";
for (int index = 0; index < count; index++)
cout << correctAnswers[index] << " ";
cout << endl;
system ("pause");
return 0;
}
You never check to see if the stream is ever initialized to the desired state. I would begin by checking whether the stream is able open the given argument: if(inputFile.is_open)
correctAnswers is an array of int, you are trying to copy onto it strings coming from the file. I suggest you to use an auxiliary variable to store the line grabbed from the file, then manipulate it as you want. Also, you probably want to make sure not to exceed the end of file limits...

C++ program not moving past cin step for string input

I'm obviously not quite getting the 'end-of-file' concept with C++ as the below program just isn't getting past the "while (cin >> x)" step. Whenever I run it from the command line it just sits there mocking me.
Searching through SO and other places gives a lot of mention to hitting ctrl-z then hitting enter to put through an end-of-file character on windows, but that doesn't seem to be working for me. That makes me assume my problem is elsewhere. Maybe defining x as a string is my mistake? Any suggestions about where I'm going wrong here would be great.
Note: sorry for the lack of comments in the code - the program itself is supposed to take in a series of
words and then spit back out the count for each word.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using std::cin;
using std::cout; using std::endl;
using std::sort;
using std::string; using std::vector;
int main()
{
cout << "Enter a series of words separated by spaces, "
"followed by end-of-file: ";
vector<string> wordList;
string x;
while (cin >> x)
wordList.push_back(x);
typedef vector<string>::size_type vec_sz;
vec_sz size = wordList.size();
if (size == 0) {
cout << endl << "This list appears empty. "
"Please try again." << endl;
return 1;
}
sort(wordList.begin(), wordList.end());
cout << "Your word count is as follows:" << endl;
int wordCount = 1;
for (int i = 0; i != size; i++) {
if (wordList[i] == wordList[i+1]) {
wordCount++;
}
else {
cout << wordList[i] << " " << wordCount << endl;
wordCount = 1;
}
}
return 0;
}
If you're on windows ^Z has to come as the first character after a newline, if you're on a unixy shell then you want to type ^D.
The input portion of your code works. The only real problem I see is with the loop the tries to count up the words:
for (int i = 0; i != size; i++) {
if (wordList[i] == wordList[i+1]) {
The valid subscripts for wordList run from 0 through size-1. In the last iteration of your loop, i=size-1, but then you try to use wordList[i+1], indexing beyond the end of the vector and getting undefined results. If you used wordList.at(i+1) instead, it would throw an exception, quickly telling you more about the problem.
My guess is that what's happening is that you're hitting Control-Z, and it's exiting the input loop, but crashing when it tries to count the words, so when you fix that things will work better in general. If you really can't get past the input loop after fixing the other problem(s?), and you're running under Windows, you might try using F6 instead of entering control-Z -- it seems to be a bit more dependable.
I pretty much always use getline when using cin (particularly when what I want is a string):
istream& std::getline( istream& is, string& s );
So, you'd call getline(cin, x) and it would grab everything up to the newline. You have to wait for the newline for cin to give you anything anyway. So, in that case, your loop would become:
while(getline(cin, x))
wordList.push_back(x);
cin does not accept blank space or line breaks so execution of cin does not complete unless you enter something , here is a test program that gives you what you want
#include "stdafx.h"
#include<iostream>
#include <string>
#include <sstream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string str = "";
while(std::getline(cin, str) && str!="")
{
cout<<"got "<<str<<endl;
}
cout<<"out"<<endl;
cin>>str;
return 0;
}