Reading integers into an array C++ - c++

I'm trying to read a file called numbers.txt and insert the integers into an array. My code outputs only the last integer in the file.
//numbers.txt
1
10
7
23
9
3
12
5
2
32
6
42
My code:
int main(){
ifstream myReadFile;
myReadFile.open("/Users/simanshrestha/Dev/PriorityQueue/PriorityQueue/numbers.txt");
char output[100];
int count = 0;
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
//cout<< output << endl;
count++;
}
for(int i=0;i<count;i++)
{
cout << output[i];
}
cout<<endl;
}
cout << "Number of lines: " << count<< endl;
myReadFile.close();
return 0;
}

int main()
{
std::ifstream myReadFile;
myReadFile.open("/home/duoyi/numbers.txt");
char output[100];
int numbers[100];
int count = 0;
if (myReadFile.is_open())
{
while (myReadFile >> output && !myReadFile.eof())
{
numbers[count] = atoi(output);
count++;
}
for(int i = 0; i < count; i++)
{
cout << numbers[i] << endl;
}
}
cout << "Number of lines: " << count<< endl;
myReadFile.close();
return 0;
}
try this.
atoi is a function Convert a string to an integer.

you can try this also: same as the bottom
basically you need to define a "temp" or holder variable to store your data. and anything inside a loop stays in that loop cause of scope resolution, and overriding data each time you store it since it doesn't exit at all.
Hope this helps!
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
const string FILE = "your file name here";
int main()
{
ifstream myReadFile;
myReadFile.open(FILE);
char output[100];
int numbers[100];
int count = 0;
if (myReadFile.is_open()){
while (myReadFile >> output && !myReadFile.eof()) //not stopping until we reach end of file
{
numbers[count] = atoi(output); //converts string to int
count++;
}
for(int i = 0; i < count; i++)
{
cout << numbers[i] << endl;
}
}
cout << "Number of lines: " << count+1 << endl; //total number of lines in file
myReadFile.close();
else{ cout << "Error: File name not loaded" << endl;}
return 0;
}

May I hazard a guess that your code is getting the sum of all the numbers and it is saved in the 1st element of your array?
May I also guess you want the number of the first line in the text file to be saved in the first element of the array? 2nd line in 2nd element so on and so forth?
If so, the following code might need updating:
myReadFile >> output;
to
myReadFile >> output[count];
I'm quite sure this will work in C and assume this would work in C++ too
updated:
another thing to add is to have 2D array like this:
char output[100][5]; //assuming our number is at most 5 char long

Related

Comparing an element of a string array with a string

So, while practicing strings i came across this question that gave me, "n" number of strings and it asked me to output strings in increasing alphabetical order.
Example :
Input>>
4 // number of string
abcdef ghi // string 1
ccdef // string 2
bcdcas // string 3
xcxvb // string 4
vxzxz // string 5
This will output only strings 1,2,4 because we have to print string in an increasing alphabetical way.
string 1 < string 2 < string 4.
(string 3 is smaller than string 2, and hence the output)
So i coded the problem without using string array and it worked, but when i applied the same approach the output was not correct.
Maybe i don't know something about string array that you guys can help me with.
Here is the code for you guys :
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
string array[n];
cin.ignore();
for(int i=0; i<n;i++){
getline(cin , array[i]);
}
cout << array[0] << endl;
string maximum;
for(int i = 0; i<n; i++){
maximum = array[0];
if(array[i] > maximum){
maximum = array[i];
cout << maximum << endl;
}
}
}
Here is the code that worked without any problems:
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int n;
cin >> n;
string text;
cin.ignore();
string max = "";
for(int i=0; i<n;i++){
getline(cin , text);
if(text>max){
max = text;
cout << text << endl;
}
}
}
I've used your working code as a starting point. Try to avoid c-style arrays and use one of the C++ containers (like std::vector) instead.
#include <iostream>
#include <string>
#include <vector>
int main()
{
int n;
std::string text;
std::vector<std::string> array;
std::cout << "Enter number of strings: ";
std::cin >> n;
std::cin.ignore();
for(int i=1; i<=n;i++) {
std::cout << "Enter string " << i << ": ";
std::getline(std::cin, text);
// check if we already have stored anything in the array and
// then check if text is <= than the last element in the array.
// if so, continue will skip to the next iteration in the for-loop
if(array.size()>0 && text<=array.back()) continue;
std::cout << "saved " << text << "\n";
array.emplace_back(std::move(text));
}
std::cout << "All saved strings:\n";
for(auto& s : array) {
std::cout << s << "\n";
}
}

Returning garbage numbers and I don't know why

I'm trying to create a program that reads in numbers from a file into an array, reverse the order of the numbers in the array and then outputs those reversed numbers into a different file. I was able to get the program to work when I already knew how many numbers were in the file but I am having difficulty when I switch my loop to trying to detect the EOF(End of file). When I run this code it will print two of the numbers from the file and the rest are garbage values. Any Help?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int NUMS = 5;
void reverseArray(int number[], int first, int last)
{
int temp;
if (first >= last)
{
return;
}
temp = number[first];
number[first] = number[last];
number[last] = temp;
reverseArray(number, first + 1, last - 1);
}
int main()
{
//Create file objects
ifstream inputFile;
ofstream outputFile;
string inputName;
string outputName;
//Prompt user for file names
cout << "What is the name of the input file?" << endl;
getline(cin, inputName);
cout << "What would you like the output file to be called?" << endl;
getline(cin, outputName);
//open user named files
inputFile.open(inputName);
outputFile.open(outputName);
int numsFromFile;
int numbers[NUMS];
int fileCount = 0;
/*
//read in numbers from a file ********THIS WORKS BUT WHEN I CHANGE IT BELOW IT DOES NOT******
for (int count = 0; count < NUMS; count++)
{
inputFile >> number[count];
}
*/
//Try to read numbers in detecting the EOF
while (inputFile >> numsFromFile)
{
inputFile >> numbers[fileCount];
fileCount++;
}
//print numbers to screen
for (int count = 0; count < fileCount; count++)
{
cout << numbers[count] << endl;
}
//reverse array
reverseArray(numbers, 0, 4);
cout << "Reversed is: " << endl;
//print reversed array
for (int count = 0; count < NUMS; count++)
{
cout << numbers[count] << endl;
}
//output numbers to a file
for (int count = 0; count < NUMS; count++)
{
outputFile << numbers[count] << endl;
}
outputFile.close();
inputFile.close();
return 0;
}
There is a bug in the lines:
while (inputFile >> numsFromFile)
{
inputFile >> numbers[fileCount];
fileCount++;
}
You end up reading and discarding the 1st number, the 3rd number, the 5th number, etc. Change it to:
while (inputFile >> numsFromFile)
{
numbers[fileCount] = numsFromFile;
fileCount++;
}

Read a text file of numbers and store into an array of integers in C++

I need to store an array of integers from a text file, but I can't find what I need to do for it exactly. I think I have the basis of the code set up, but I think I need to convert the elements into integers or something?
My output is my list :
50
0
20
10
18
-5
15
22
34
-1
But my "sorted" list ends up being -1, and a series of large negative numbers.
I troubleshooted it to being something wrong with the array.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int counter=0,n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
datafile.close();
//////////////////////////////
//bubbleSort(array1, n);
//selectionSort(array1, n);
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}
Never use eof(), since it leads to wrong programs. See https://stackoverflow.com/a/5837670 for the reason.
while (n < 30 && datafile >> array1[n]) {
cout << array1[n] << endl;
n++;
}
{
int excess;
if (datafile >> excess) {
cerr << "error: data file too large\n";
return;
}
}
That way, the n will be correct at the end of the program.
Your code is all good except :
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
It should be:
while (!datafile.eof()) {
datafile >> array1[n];
if ( datafile.fail() ) break;
cout << array1[n] << endl;
n++;
}
Only a single index variable(n) is required to parse/store into a 1D array.
The increment statement n++ in a while should always be the last one so that you are working on the current element and not the next.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[n];
if (datafile.fail()) break;
cout << array1[n] << endl;
n++;
}
datafile.close();
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}

Unexpected abort in C++

I have a piece of code I'm running in Cygwin in C++ I'm compiling using
g++ -o program program.cpp
And it is returning an error that reads 'Aborted (core dumped)'. It is intended to take a file name as input through a command line argument, count all the unique words and total words in the file, and prompts the user to input a word and counts how many times the word that they input occurs. It's only intended to use C++ streams for input/output.
#include <fstream>
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main(int argc, char *argv[])
{
string filename;
for( int i = 1; i < argc; i++){
filename+=argv[i];
}
ifstream file;
file.open(filename.c_str());
if (!file)
{
std::cerr << "Error: Cannot open file" << filename << std::endl;
return 1;
}
string* words;
int* wordCount;
int wordLength = 0;
string curWord = "";
bool isWord;
int total = 0;
char curChar;
string input;
while(!file.eof())
{
file.get(curChar);
if (isalnum(curChar)) {
curWord+=tolower(curChar);
}
else if (!curWord.empty() && curChar==' ')
{
isWord = false;
for (int i = 0; i < wordLength; i++) {
if (words[i]==curWord) {
wordCount[i]++;
isWord = true;
total++;
}
}
if (!isWord) {
words[wordLength]=curWord;
wordLength++;
total++;
}
curWord="";
}
}
file.close();
// end
cout << "The number of words found in the file was " << total << endl;
cout << "The number of unique words found in the file was " << wordLength << endl;
cout << "Please enter a word: " << endl;
cin >> input;
while (input!="C^") {
for (int i = 0; i < wordLength; i++) {
if (words[i]==input) {
cout << wordCount[i];
}
}
}
}
You never allocated any space for words and wordCount to point to. It should be:
#define MAXWORDS 1000
string *words = new string[MAXWORDS];
int *wordCount = new int[MAXWORDS];
and then at the end of the program you should do:
delete[] wordCount;
delete[] words;
or you can allocate a local array:
string words[MAXWORDS];
int wordCount[MAXWORDS];
But you could do it more simply by using std::map to map the string to a count. This will automatically grow as needed.

ifstream runtime error when attempting to save the data into array

I'm having a problem when I try to read the external text file.
The displayed text is correct but when it comes to saving the data into an array, it seems to be wrong.
My input numbers are 4 2 8 0 2 3 0 4 0 5, but after looping through the array, a[i], only '48' appears.
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
void begin ();
void Process (string);
using namespace std;
int main()
{
begin();
system("pause");
return 0;
}
void begin (void){
string file = "data.txt";
Process(file);
}
void Process (string file)
{
int i=0,ch, n = 0, temp, a[50];
ifstream infile;
infile.open(file.c_str());
The error seems to be caused from here.
if(infile.is_open())
{
cout << "File to be read: " << file << endl;
cout << "\n\n";
infile >> temp;
while(!infile.fail())
{
cout << temp << " ";
infile >> temp;
a[i] = temp;
i++;
n++;
}
cout << "\n\n";
cout << "This file has " << n << " numbers. \n\n";
}
else
cout << "The file isn't available! \n\n";
infile.close();
When I try to output the result, only 48 appears.
for (int z = 0; z < i; z++)
{
cout << a[i] << endl;
}
}
I'm new here. Please help. Thanks in advance.
Your display loop is using i instead of z to index into a (this should be a good lesson on why variable naming is important!) Change your display loop to this:
for (int z = 0; z < i; z++)
{
cout << a[z] << endl;
}
There are potentially more issues with your code, but this seems to be what is blocking you. Consider renaming i and a to more meaningful things. The time you will spend typing will always be dwarfed by the time you spend trying to understand what you meant.
Consider this loop
for (int z = 0; z < i; z++)
{
cout << a[i] << endl;
}
You always output one element a[i] instead of a[z]. Moreover element with index i was not assigned. The last assigned element is a[i-1].
Apart from this you do not save the first entered number in the array. You start to save entered data from the second number.
infile >> temp; // <== this value was not assigned to an element of the array
while(!infile.fail())
{
cout << temp << " ";
infile >> temp;
a[i] = temp;
Also this statement inside the loop
infile >> temp;
can result in error. So after that there is no sense to write
a[i] = temp;
because nothing was entered and in fact you will store the previous number in the next element.