Reading multiple integers from a text file line using scanf - c++

Here's the code in question:
int participant_count; int budget; int hotel_count; int week_count;
int minimum_cost = INT32_MAX;
while (cin >> participant_count >> budget >> hotel_count >> week_count) {
int hotel_price;
int *available_bed_count = new int[week_count];
while (cin >> hotel_price) {
for (int i = 0; i < week_count; i++) {
scanf("%d", available_bed_count[i]);
if (available_bed_count[i] >= participant_count) {
minimum_cost = min(minimum_cost, (hotel_price * participant_count));
}
}
}
delete []available_bed_count;
}
and here's the textfile that I'm reading from. I've drawn an arrow to highlight the exact line that I cannot properly handle
3 1000 2 3
200
0 2 2 <---
300
27 3 20
5 2000 2 4
300
4 3 0 4
450
7 8 0 13
Unfortunately, my code breaks and nothing gets output to my file once the scanf function is reached and I don't know why. Could someone please tell me what I'm doing wrong? I'm thinking that there might be an issue with using 'cin' and 'scanf' together where I might be attempting to read from the same line that 'cin' read from, but I don't really know.

Related

Read to array from table in text file, while skipping specific column

I am trying to read the contents of a text file into 2D array in C++. The file contains 125 rows with 21 columns of integers (a table of integers). I'm to read this into an array that is 125 rows of 20 columns, skipping column 21 of the file.
I defined the size of the array with variables, but it just reads column 21 into the next row, ignoring the new line. I need it to start each row in the array at the start of the new line from the file but ignore the last item in the table.
I'm not sure if I'm looking for it to skip column 21, or if I'm looking for it to start reading each column at a new line (or both?)
Text file looks like (is this called a matrix?) and it's number separated by 1 space and \n at end.
(The text file was generated by a program to generate rows of 20 numbers and the sum.)
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 93
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 93
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 93
" etc
Other solutions I've found can be difficult for me to understand because people write their variables and functions non-descriptively. Some solutions require advanced methods I'm not supposed to use as well, such as vectors and string manipulation. I have currently learned everything before "pointers" so I can only use solutions I've learned in class. I've learned functions, arrays, search/sort, and basics like operators, loops, variables, etc. I'm not supposed to use vectors for this or string manipulation.
I will (eventually) have to sum the numbers in the array (after I extract the first 20 of each row from the file) so to compare the sum from the array final column to the last integer in each row of the file (which is a sum).
My function is (note: We are using namespace std)
void readArray() {
ifstream infile("tableofintegers.txt");
for (int rowcount = 0; rowcount < ROWS; rowcount++) // row loop
{
for (int colcount = 0; colcount < COLS; colcount++) // column loop
{
infile >> twoDArray[rowcount][colcount]; // read to array
}
}
}
These are variables:
const int ROWS = 125;
const int COLS = 20;
I tried this but got a runtime error
file >> array[row][col];
file.ignore(10, '\n');
The error when I tried file.ignore
C:\path\matrix.exe (process 27316) exited with code -2147483645.
Not only is there an error, but it still "wraps" the read starting line two with the sum (last digit) of line 1.) As you can imagine, as this iterates, it keeps pushing the data over further and further.
I expected for the program to stop reading when it reached the limit of the array columns (20) then continue at the next line, but it didn't. My brain tells me something's not logical about that expectation, yet I have a dissonance or something going on. I can't really wrap my head around it. I also tried file.ignore which I expected would ignore 10 characters after the 20th column up to new line, but it just kicked an error and still wrapped.
Note: I'm printing the array to the console. Here is my code for that.
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLS; col++)
{
cout << setw(5) << dataArray[row][col];
}
cout << endl;
}

File Reading Function only Reads First line then quits

Problem Description
Basically, Inside of my "Roster.h" header file, i have an array of "Student" objects from the student class ( which includes the functions changeScore, SetID, setTotal,setLetterGrade). In the function that will be attached below, it is only reading the first line of data and then quitting at the while condition. I've been staring at this issue for hours now and could use a second (or third) pair of eyes. Any criticism is also appreciated, as i know that i am not the most effective programmer.It should be noted that "m_studentnum",is private data that is initialized to 0 in the constructor. Thanks in advance!
Code
void Roster::readStudentRecord(string file)
{
ifstream in;
string studentID;
string line;
int ola, cla, quiz, homework, exam, bonus, total, final = 0;
in.open(file.c_str());
getline(in, line);
while (in >> studentID) {
in >> cla >> ola >> quiz >> homework >> exam >> bonus >> total >> final;
m_students[m_studentNum].Student::setID(studentID);
m_students[m_studentNum].Student::changeScore(Student::CLA, cla);
m_students[m_studentNum].Student::changeScore(Student::OLA, ola);
m_students[m_studentNum].Student::changeScore(Student::QUIZ, quiz);
m_students[m_studentNum].Student::changeScore(Student::HOMEWORK, homework);
m_students[m_studentNum].Student::changeScore(Student::EXAM, exam);
m_students[m_studentNum].Student::changeScore(Student::BONUS, bonus);
total = cla + ola + quiz + homework + exam + bonus;
m_students[m_studentNum].Student::setTotal(total);
if (total >= 90) {
m_students[m_studentNum].Student::setLetterGrade('A');
}
else if (total >= 80 && total < 90) {
m_students[m_studentNum].Student::setLetterGrade('B');
}
else if (total >= 70 && total < 80) {
m_students[m_studentNum].Student::setLetterGrade('C');
}
else if (total >= 60 && total < 70) {
m_students[m_studentNum].Student::setLetterGrade('D');
}
else {
m_students[m_studentNum].Student::setLetterGrade('F');
}
m_studentNum++;
}
}
Data file
-note that i am doing a getline to get read in the headline for the data column's
ID CLA OLA Quiz Homework Exam Bonus Total FinalGrade
c088801 10 15 4 15 56 5
c088802 9 12 2 11 46 2
c088803 8 10 3 12 50 1
c088804 5 5 3 10 53 3
c088805 3 11 1 10 45 0
c088806 8 14 2 11 40 -1
c088807 4 12 2 12 48 -2
c088808 10 10 3 11 36 0
c088809 8 8 3 11 39 0
c088810 6 9 4 9 47 3
c088811 8 7 3 13 41 3
c088812 4 11 3 11 37 1
The "Total" and "FinalGrade" columns are empty, and you unconditionally try to read them.
When you attempt to do that, the input will contain the "ID" from the next line, and as that is not an integer, leading to the failbit flag being set for the stream which causes the loop condition to be false and the loop to end.
One possible solution is to read the while line into a string, put that string into an std::istringstream object, and read the non-empty columns as you do now. Then try to read the possibly empty columns from the input string stream.
Another solution, if those columns are supposed to be empty, is to simply not read them.

Blank Screen while inputting from file c++

So i am working on my project and i am facing a problem. Every time i try to input data from file in c++ i got blank screen
The code :
int main() {
string make[1000],model[1000],partName[1000];
int partNo[1000],quantity[1000];
double price[1000];
int i = 0;
ifstream myFile("file.txt");
while (!myFile.eof())
{
myFile >> make[i] >>model[i]>> partNo[i] >>quantity[i]>> price[i]>>partName[i];
i++;
}
for (int j = 0;j < i;j++)
cout << make[j] <<"\t"<<model[j]<<"\t"<< partNo[j] <<"\t"<<quantity[j]<<"\t"<< price[j]<<"\t"<<partName[j]<<endl;
return 0;
}
a sample from data file :
Pajero NA1H25 1 26 3.65 BLADE W/S WIPER
Pajero NA1S25 2 12 65.7 OIL SEAL-T/M CASE
Pajero NA3H25 3 20 14.6 OIL SEAL-DIST
Pajero NA3H25 4 26 10.95 DISC-CLUTCH
Pajero NC3V25 5 13 14.6 FUSIBLE LINK
Pajero ND0000 6 12 3.65 WEATHERSHIELD PKGE-L
Pajero ND1V45 7 10 32.85 SEAL & BOOT KIT
Pajero ND1Z45 8 24 62.05 FUSIBLE LINK
Pajero ND1Z45 9 9 18.25 COVER-HANDLE LH
Pajero ND1Z45 10 6 3.65 PIPE ASSY-OIL
anyone can help ??
Input with operator >> to a std::string will only read a single word.
This means that the first input will read "BLADE" and leave "W/S WIPER" in the input buffer, and the next read will start from there. Eventually, an input operation for a numeric field will try to read letters, and fail to read.
After that the stream is in a bad condition and nothing else is read, even though myfile.eof() is not true (but myfile.fail() is). There you have an infinite loop. See Why is iostream::eof inside a loop condition considered wrong?

Values of array randomly change

So I have a text file which has information about basketball players and it looks like this:
8
9 5 7 -5 13 -4 11
7 5 -3 12 -5 17 -3
25 7 12 -3 5 -5 7 -5 3
14 5 12 -3 10 -7 8
5 1 -40
33 5 15 -5 9 -3 8
11 5 -12 8 -5 12 -3
13 5 3 -4 25 -5 3
First integer in the first line shows how many players are there. In every other line the first integer is the number of the player, the second integer shows how many more integers there are in the line and each of the following integers shows if the player is playing (if the integer is positive) or sitting on the bench (if the number is negative).
I want to read the info to an array of structures which look like this:
struct player
{
int nr;
int k;
int bus[];
};
I've written a function to do so:
void skaitymas(int &n, player mas[])
{
ifstream duom("U1.txt");
duom >> n;
for (int i=0; i < n; i++) {
duom >> mas[i].nr >> mas[i].k;
for (int f=0; f < mas[i].k; f++) {
duom >> mas[i].bus[f];
}
}
}
When I run it the program seems to work, however the arrays of structures save unexpected values. After adding some cout commands in random places, I found out that it saves the correct values to the array the first time, first for loop loops, but after some iterations it changes the values of the previous arrays. For example, when i in the for loop equals 1 then mas[1].bus[0] is saved to be -3, as it should be, however after i changes to 2, mas[1].bus[0] changes to 25.
I would appreciate it if you would help me to figure it out, why the numbers in the arrays change to other random numbers from the text file, even if I don't do anything to them.
There are several problems with your code. The most obvious is
that int bus[] declares a variable with an incomplete type,
and it is illegal in C++ to declare a member variable with an
incomplete type. Unless your compiler is seriously broken, this
shouldn't compile; at the very latest, you should get an error
when you write mas[i], since there is no possible way of doing
pointer arithmetic on a pointer to an incomplete type. The way
to declare your class is:
struct Player
{
int nr;
std::vector<int> bus;
};
Once you do this, you should be able to compile. Still, it's
very poor C++ to read in counts of the following elements. The
correct way of doing this would be to drop the counts in the
file: the number of lines is the number of players, and the
number of integers following the first in the line is the number
of integers following the first in the line. If you do this,
you end up with something like:
std::vector<Player> skaitymas()
{
std::ifsteram duom( "U1.txt" );
if ( !duom.is_open() ) {
// Some sort of error handling, maybe an exception.
}
std::vector<Player> results;
std::string line;
while ( std::getline( duom, line ) ) {
std::istringstream s( line );
int nr;
s >> nr;
if ( !s ) {
// Format error...
}
results.push_back(Player{ nr });
while ( s >> nr ) {
results.back().bus.push_back( nr );
}
}
return results;
}
Everything is done dynamically (which is very simple in C++).

C++ input data into a struct variables from data file

I have a text file containing names and numbers. The name or the string contains 15 chars and I need to put it to the string. I'm working with structures.
struct grybautojas{
string vardas;
int barav, raudon, lep, diena;
}gryb[100];
After that, there are simple calculations which is done right, the problem is, it only reads everything once. After taking a first "box" of information, it just stops. Everything else in the result file is either blank as a string or 0 as an integer.
Here's my input function:
void ivedimas(){
char eil[16];
int b,r,l;
inFile >> n;
inFile.ignore();
for(int i=0;i<n;i++){
inFile.get(eil,15);
gryb[i].vardas=eil;
inFile >> gryb[i].diena;
gryb[i].barav=0, gryb[i].raudon=0, gryb[i].lep=0;
for(int m=0;m<gryb[i].diena;m++){
inFile >> b >> r >> l;
gryb[i].barav+=b, gryb[i].raudon+=r, gryb[i].lep+=l;
}
inFile.ignore();
}
inFile.close();
}
And here's the file containing data:
4
Petras 3
5 13 8
4 0 5
16 1 0
Algis 1
9 6 13
Jurgis 4
4 14 2
4 4 15
16 15 251
1 2 3
Rita 2
6 65 4
4 4 13
What's the problem?
inFile.get(eil,15);
Rita 2
Petras 3
00000000011111
12345678901234
I don't count 15, I count 14. Also, some of your lines seem to have a space at the end. You should rewrite your input logic to be much more robust. Read lines and parse them.
This line:
inFile.get(eil,15);
is reading the number that follows the name.
When you try to read the number (3 in your example), you get the next one (5) instead.