Getting array values from separate text file - c++

This is my first attempt at getting a bunch of values from a separate text document. I have a separate text file named P.txt with the following values 13 49
16 2
4 0
90 60
40 20
60 -100
7 1
5 9
3 3
15 -22
11 7
12 3
I have never tried to get data from an outside file to put into an array and while working I keep getting errors on line 15 which is:
read_data(int nums[], int size);
Visual studio says that it is expecting a ")" after int and that the read_data function does not take 0 arguments. Can anyone explain these errors to me and help guide me in the right direction? Thanks!
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
void read_data(int nums[], int size);
int main()
{
const int size = 24;
ifstream dataIn;
double lab[size];
cout << "The numbers on file are:\n ";
read_data(int nums[], int size);
system("PAUSE");
return 0;
}
void read_data(int nums[], int size)
{
ifstream dataIn;
dataIn.open("P.txt");
if( dataIn.fail() )
{
cout << "File does not exist." << endl;
exit(1);
}
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> nums[count];
}
dataIn.close(); }

The problem is in the line read_data(int nums[],int size);
You cannot declare a variable in a function call.
Also, you cannot use system("pause") without stdlib.h or cstdlib
Use this instead :
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void read_data(int nums[], int size);
int main()
{
const int size = 24;
ifstream dataIn;
double lab[size];
int nums[size];
cout << "The numbers on file are:\n ";
read_data(nums, size);
system("PAUSE");
return 0;
}
void read_data(int nums[], int size)
{
ifstream dataIn;
dataIn.open("P.txt");
if( dataIn.fail() )
{
cout << "File does not exist." << endl;
exit(1);
}
int count;
for ( count = 0; count < size; count++ )
{
dataIn >> nums[count];
}
dataIn.close(); }

Related

Value pushed to the stack is not what I pop out C++

I'm new to c++, I'm trying to read values from a text file and push only the integers to a stack. The issue I'm having is that when I do a pop() the value that comes out of the stack is different.
For example if I push a 4, when I do a pop it comes out as 52.
What am I doing wrong and how can I fix it?
IntegerStack.cpp
#include "IntegerStack.h"
#include <cstdlib>
using namespace std;
IntegerStack::IntegerStack()
{
used = 0;
}
void IntegerStack::push(int entry)
{
data[used] = entry;
++used;
}
int IntegerStack::pop()
{
--used;
return data[used];
}
int IntegerStack::peek() const
{
return data[used-1];
}
IntegerStack.h
#ifndef INTEGERSTACK_H
#define INTEGERSTACK_H
#include <cstdlib> // Provides the type size_t.
using namespace std;
class IntegerStack
{
public:
// MEMBER CONSTANT
static const std::size_t CAPACITY = 100;
// DEFAULT CONSTRUCTOR
IntegerStack( ); // Inline
// MODIFICATION MEMBER FUNCTIONS
void push ( int entry );
int pop ( );
// CONSTANT MEMBER FUNCTIONS
std::size_t size ( ) const { return used; } // Inline
bool is_empty ( ) const { return used == 0; } // Inline
int peek ( ) const;
private:
// DATA MEMBERS
int data[CAPACITY];
std::size_t used;
};
#endif // INTEGERSTACK_H
main.cpp
#include <fstream>
#include <iostream>
#include "IntegerStack.h"
using namespace std;
int main()
{
string content;
ifstream inputFile;
cout << "Enter input file name: ";
cin >> content;
IntegerStack operandStack;
// Open file
inputFile.open(content.c_str());
if(inputFile)
{
// Place values in the stack
while(getline(inputFile,content))
{
cout << "Expression: " << content << endl;
for (int i = 0; i < content.size(); i++)
{
if(isdigit(content[i]))
{
cout << "Adding " << content[i] << " to operandStack" << endl;
operandStack.push(content[i]);
int number = operandStack.pop();
cout << "The integer we just pushed: " << number << endl;
}
else
{
// add it to operatorStack
}
}
}
}
// Close file
inputFile.close();
return 0;
}
inix.dat
8 + 4 / 2
( 7 * 4 ) - 2
OUTPUT
Enter input file name: infix.dat
Expression: 8 + 4 / 2
Adding 8 to operandStack
The integer we just pushed: 56
Adding 4 to operandStack
The integer we just pushed: 52
Adding 2 to operandStack
The integer we just pushed: 50
Expression: ( 7 * 4 ) - 2
Adding 7 to operandStack
The integer we just pushed: 55
Adding 4 to operandStack
The integer we just pushed: 52
Adding 2 to operandStack
The integer we just pushed: 50
Process returned 0 (0x0) execution time : 4.762 s
Press any key to continue.
I was able to solve this by changing operandStack.push(content[i]); to operandStack.push(content[i]- '0');

Read Files using a function C++

I'd like to know how to read a file using streams but also using them inside a function.
So far my code is;:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
void burbuja(int[]);
void imprimeArreglo (int[],int);
void leeArchivo(string&);
int arreglo[10];
int i;
void burbuja (int a[])
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<i;j++)
{
if(a[i]>a[j])
{
int temp=a[i]; //swap
a[i]=a[j];
a[j]=temp;
}
}
}
}
void imprimeArreglo(int a[],int tam)
{
for(int i=0;i<tam;i++)
cout << a[i] << " ";
}
void leeArchivo(string& nombre)
{
string filename = nombre;
ifstream myfile(filename);
string line;
if (myfile.is_open()) {
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
}
int main()
{
string nombre = "arr.txt";
leeArchivo(nombre);
cin >> i ;
return 0;
}
I'd like to be able to call leeArchivo("arr.txt") from the main method.
With this I get the errors:
Error: bubble.cpp(37,14):'ifstream' is not a member of 'std'
Error: bubble.cpp(37,19):Statement missing ;
Error: bubble.cpp(39,20):Undefined symbol 'file'
Error: bubble.cpp(39,25):Could not find a match for 'std::getline(undefined,std::basic_string<char,std::string_char_traits<char>,std::allocator<char>>)'
What am I missing here? (I'm new to C++)
The file I'm trying to read has the following structure:
<number>
<number> <number> <number> ...
E.G.:
5
19 28 33 0 1
=========================================
EDIT:
I'm using Borland C++ 5.02
EDIT 2:
Updated code, using Geany Now error is: BUBBLE.cpp:38:25: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'
That's particularly odd behavior with ifstream. Try this edit:
void leeArchivo(const string&);
void leeArchivo(const string& nombre)
{
ifstream file(nombre.c_str());
string line;
while(getline(file,line)) {
cout << line << endl;
}
}
int main()
{
leeArchivo("arr.txt");
return 0;
}
Also, use:
#include <cstdlib>
Instead of:
#include <stdlib.h>

C++ function overloading cannot identify char

When I input two integers, the output is correctly their difference. However when I enter a string and a char, instead of returning how many times the char appears in the string, it returns -1, which is the out put for error. Could anyone please help me? It's just my second day learing c++...
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s[])
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s[0],1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
if(std::cin>> c[200] >> d){
mycount(a,b);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
Hint - what will this program print?
#include <iostream>
using namespace std;
int main()
{
char c[200],d;
cout << sizeof(c) << endl;
cout << sizeof(d) << endl;
return 0;
}
Answer:
200
1
That declaration does not do what you think it does - c is an array of 200 chars, d is a single char. It's a feature of the C declaration syntax, same as:
int *c, d;
c is a pointer to int, d is an int.
Since you are doing C++, why not make your life easier and use std::string instead?
A few changes should fix your problems. First when inputting an array with cin use getline and call ignore right before hand. I find it easier to pass s as a char instead of an array of size one make sure your call your second my count with c and d instead of a and b.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
void mycount(int a, int b)
{
std::cout<< a - b <<std::endl;
}
void mycount(char str[], char s)
{
int len,i;
int sum=0;
len = strlen(str);
for (i=0;i<len;i++){
if (strncmp(&str[i],&s,1) == 0){
sum = sum + 1;
};
};
printf("results: %d times\n",sum);
}
int main()
{
int a,b;
char c[200],d;
if(std::cin>> a >> b){
mycount(a,b);
}
std::cin.ignore();
if(std::cin.getline (c,200) && std::cin >> d){
mycount(c,d);
}
else{
std::cout<< "-1" <<std::endl;
}
std::cin.clear();
std::cin.sync();
}
These changes should fix it.

C++ File I/O and Pointers

I tried to create a program that uses an input file 'cardList.txt' that contains:
Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly
and I wanted to sort this alphabetically by last name.
main:
#include <iostream>
#include <fstream>
#include <string>
#include "insertsortFunct.h"
using namespace std;
int main(void){
ifstream inData;
ofstream outData;
const int listSize = 5;
char cardList[listSize][25];
instruct();
openFile(inData, outData);
buildList(cardList, inData);
inData.close();
sortList(cardList, listSize);
cout << endl << "Your list is sorted" << endl;
writeFile(cardList, outData);
outData.close();
return 0;
}
I defined these functions in a separate file:
#include "insertsortFunct.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void instruct(void){
cout << "The program insertSort.cpp reads the file, cardList.txt " <<
"into an array and" << endl;
cout << "sorts the array using the selection sort algorithm." << endl;
cout << "The sorted array is written to a file named cardList.srt." <<
endl;
}
void openFile(ifstream& inputFile, ofstream& outputFile){
inputFile.open("cardsList.txt");
if(!inputFile.is_open())
exit(1);
outputFile.open("cardsList.srt");
if(!outputFile.is_open())
exit(1);
}
void buildList(char (*array)[25], ifstream& inputFile){
for (int i = 0; i < 5; i++)
inputFile >> array[i];
}
void sortList(char (*list)[25], int length){
int firstOutOfOrder, location;
char temp[25];
for (firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++){
location = firstOutOfOrder;
while ( location > 0 && list[location - 1] > list[location]){
temp[25] = list[location][25];
list[location][25] = list[location - 1][25];
list[location - 1][25] = temp[25];
location--;
}
}
}
void writeFile(char (*array)[25], ofstream& outputFile){
for (int i = 0; i < 5; i++)
outputFile << array[i];
}
However my program only prints the instruct(); statements and nothing else appears to happen. This program is supposed to a create a file cardList.srt with the sorted list and that does not appear in my directory after compiling.
Either inputFile.is_open() or outputFile.is_open() return false and hence exit() is called.

Problems with fstream

I'm writing a vector array to an ofstream file, however certain values aren't getting written, I.E.:
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main (){
char * hold = new char [100];
vector<double> fx(2049);
ifstream inputFile;
ofstream myFile;
inputFile.open("data.txt");
myFile.open("test.txt");
for (int c=0; c<2049; c++){
inputFile.getline(hold, 100);
fx[c] = atof(hold);
}
for (int c=0; c<2049; c++){
myFile << fx[c] << "\n";
}
}
Within fx, the second half is all equal to 0. (fx[1024] through fx[2048]==0). Within test.txt however, none of these 0 values are present, on the carriage return is applied. Any thoughts?
Thanks! (New to the formatting of these questions... any tips to make this more understandable would be appreciated.)
Note: I realize this program is rather redundant. The actual program has a great deal more functionality to it, this is just an area that is working incorrectly.
Try this
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#define MAX_FILE_LINES 2048
using namespace std;
//genarate random double number
double fRand()
{
double fMin = 100, fMax = 200;
double f = (double)rand();
return fMin + (f / (fMax - fMin));
}
//init file (if you need to create sample file with list of double numbers, you can use this function)
void fileInit(){
ofstream sourceFile;
sourceFile.open("D:\\source.txt");
if (sourceFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
sourceFile << fRand() << endl;
}
}
}
int main (){
string buffer;
vector<double> fx(MAX_FILE_LINES);
ifstream sourceFile;
ofstream destinationFile;
sourceFile.open("D:\\source.txt");
destinationFile.open("D:\\destination.txt");
//reading file lines to vector
int lineCount =0;
if (sourceFile.is_open())
{
while ( sourceFile.good() )
{
getline (sourceFile,buffer);
fx[lineCount] = atof(buffer.c_str());
lineCount++;
if (lineCount == (MAX_FILE_LINES-1)){
break;
}
}
sourceFile.close();
}
//write lines to new file
if (destinationFile.is_open())
{
for (int i=0; i<MAX_FILE_LINES; i++){
destinationFile << fx[i] << endl;
}
}
}
Why screw with handroll buffers for one-offs? You can't save a millionth of what it costs to think about cycles here, there's not enough waste to recoup.
Think about eliminating needless statements and unchecked failures first.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<float> data;
{
ifstream ids("source.txt",ios_base::in);
int linenr = 0;
for ( string line ; getline(ids,line) ; ) {
++linenr;
decltype(data)::value_type x;
istringstream s(line);
if ( s >> x )
data.push_back(x);
else
cerr << "crap line "<<linenr<<" ignored: " << line << '\n';
}
}
ofstream ods("object.txt");
for ( auto x : data )
ods << x << '\n';
}