this is my code, when i am reading the lines which must be stored in the class, its reading one line and storing the value of next line, I am unable to identify my mistake in the code. Please help me to correct it. the task is to skip the lines that has sentences and read the lines which has data abd store it in the class variables.
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
#include <string>
using namespace std;
class data_Read
{
public:
/* timestamp */
double time;
/*state of the signal 1 or 2*/
unsigned int state;
/*ID in hexadecimal and converted to decimal*/
std::string ID;
/* Received or transmitted message */
std::string status;
/* Message type */
std::string type;
/* byte length */
unsigned int byte_lent;
/* CAN Message */
std::string message_1;
std::string message_2;
std::string message_3;
std::string message_4;
std::string message_5;
std::string message_6;
std::string message_7;
std::string message_8;
std::string type1;
std::string type2;
std::string type3;
std::string type4;
std::string type5;
std::string type6;
std::string type7;
std::string type8;
std::string type9;
};
int main()
{
std::ifstream ifs("datatrace.txt");
data_Read data;
std::string line;
while (!ifs.eof())
{
start:
std::getline(ifs, line);
std::cout << line << std::endl;
if (!isspace(line[0]))
{
goto start;
}
std::size_t space = line.find(" ", 0);
if (space == 0)
{
int i;
for (i = 0; i <= 15; i++)
{
if (isalpha(line[i]))
{
goto start;
}
}
ifs >> data.time >> data.state >> data.ID >> data.status >> data.type >> data.byte_lent >> data.CAN_message_1 >> data.CAN_message_2 >> data.CAN_message_3 >> data.CAN_message_4 >> data.CAN_message_5 >> data.CAN_message_6;
ifs >> data.CAN_message_7 >> data.CAN_message_8 >> data.type1 >> data.type2 >> data.type3 >> data.type4 >> data.type5 >> data.type6 >> data.type7>> data.type8 >> data.type9;
cout << data.time << "\t" << data.state << "\t" << data.ID << "\t" << data.status << "\t" << data.type << "\t" << data.byte_lent << "\t" << data.CAN_message_1 << "\t" << data.CAN_message_2 << "\t" << data.CAN_message_3 << "\t";
cout << data.CAN_message_4 << "\t"<< data.CAN_message_5 << "\t"<< data.CAN_message_6 << "\t" << data.CAN_message_7 << "\t"<< data.CAN_message_8 << "\t"<< data.type1 << "\t"<< data.type2 << "\t"<< data.type3 << "\t"<< data.type4 << "\t"<< data.type5 << "\t" << data.type6 << "\t"<< data.type7 << "\t"<< data.type8 << "\t"<< data.type9 << endl;
}
}
ifs.close();
return 0;
}
and the text file contain
date Fri Sep 1 02:11:40.195 pm 2017
base hex timestamps absolute
internal events logged
// version 9.0.0
Begin Triggerblock Fri Sep 1 02:11:40.195 pm 2017
0.000000 Start of measurement
0.002893 1 201 Rx d 8 06 0D 00 B0 89 00 0D E7 Length = 227925 BitCount = 118 ID = 513
0.003133 1 280 Rx d 8 1B 0C 7C F1 E8 75 39 67 Length = 221910 BitCount = 115 ID = 640
0.006981 CAN 1 Status:chip status error active
0.006981 CAN 2 Status:chip status error active
0.007123 1 244 Rx d 8 7B 01 00 08 80 80 C0 00 Length = 233925 BitCount = 121 ID = 580
0.007148 2 B2 Rx d 8 C0 13 9A 13 D8 13 C0 13 Length = 221910 BitCount = 115 ID = 178
0.007359 1 246 Rx d 8 55 01 00 49 50 B6 7A 89 Length = 217925 BitCount = 113 ID = 582
0.007394 2 86 Rx d 8 62 00 2A 20 01 84 02 00 Length = 225925 BitCount = 117 ID = 134
the final answer
while (std::getline(file, line))
{
std::istringstream iss(line);
std::size_t space = line.find(" ", 0);
if (!isspace(line[0]))
{
iss.clear();
}
else
{
int i;
for (i = 0; i <= 12; i++)
{
if (isalpha(line[i]))
{
iss.clear();
goto start;
}
}
iss >> data.time >> data.state >> data.ID >> data.status >> data.type >> data.byte_lent >> data.CAN_message_1 >> data.CAN_message_2 >> data.CAN_message_3 >> data.CAN_message_4 >> data.CAN_message_5 >> data.CAN_message_6;
iss >> data.CAN_message_7 >> data.CAN_message_8 >> data.type1 >> data.type2 >> data.type3 >> data.type4 >> data.type5 >> data.type6 >> data.type7 >> data.type8 >> data.type9;
Related
I'm sorry this is long but I don't know what I should do to solve the problem
For the 0s being outputted I'm guessing its the contents of the other file but in 0s I just don't know how to get rid of them
This is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct Users
{
int user_id;
string fname;
string lname;
char gender;
int age;
int phone;
string address;
};
struct Contacts
{
int user_id;
int contact_with;
int contact_start;
int contact_end;
int distance;
};
void discard_line(ifstream &in)
{
char c;
do{
in.get(c);
}while(c != '\n');
}
void users(ifstream &userFile, int size, struct Users user[])
{
cout << "-----------------------------------------------------\n";
cout << "UserID\tFname\t Lname\tGender\tAge\tPhone\tAddress" << endl;
cout << "-----------------------------------------------------\n";
for(int i = 0; i < size; i++)
{
cout << user[i].user_id << "\t" << user[i].fname << "\t" << user[i].lname << "\t" << user[i].gender << "\t" << user[i].age << "\t" << user[i].phone << "\t" << user[i].address << endl;
}
//total number of users
}
void contacts(ifstream &contactfile, int size, struct Contacts contact[])
{
cout << "-----------------------------------------------------\n";
cout << "UserID\tCon/With\tDuration(s)\tDistance(cm)" << endl;
cout << "-----------------------------------------------------\n";
for(int i = 0; i < size; i++)
{
int duration = contact[i].contact_end - contact[i].contact_start;
cout << contact[i].user_id << "\t" << contact[i].contact_with << "\t\t" << duration << "\t\t" << contact[i].distance << endl;
}
}
int main()
{
int option;
const int SIZE = 1000;
int index = 0;
Users user[SIZE];
Contacts contact[SIZE];
ifstream userFile("users.txt");
ifstream contactFile("contacts.txt");
if(!userFile)
{
cout << "The file is not found" << endl;
exit(1);
}
if(!contactFile)
{
cout << "The file is not found" << endl;
exit(1);
}
discard_line(userFile);
discard_line(contactFile);
while(!userFile.eof())
{
userFile >> user[index].user_id >> user[index].fname >> user[index].lname >> user[index].gender >> user[index].age >> user[index].phone >> user[index].address;
index++;
}
while(!contactFile.eof())
{
contactFile >> contact[index].user_id >> contact[index].contact_with >> contact[index].contact_start >> contact[index].contact_end >> contact[index].distance;
index++;
}
users(userFile,index,user);
contacts(contactFile,index,contact);
return 0;
}
and the output is this:
-----------------------------------------------------
UserID Fname Lname Gender Age Phone Address
-----------------------------------------------------
1001 Ray Dixon M 46 9364652 Lokia
1002 Bryan Green M 18 9579302 Drekena
1003 Justin Dixon M 33 9353533 Lokia
1004 Lester Byrd M 45 9534695 Nasilai
1005 Santos Larson M 53 9093177 Vunuku
1006 Bryan Cobb M 42 9905139 Narocivo
1007 Eddie Watson M 20 9610408 Nabua
1008 Wesley Barton M 27 9801864 Nasigatoka
1009 Victor Mason M 50 9855386 Nukutubu
1010 Ellis Cobb M 24 9389406 Narocivo
1011 Diana Ross F 27 9940148 Vunuku
1012 Amanda Carter F 43 9506743 Nasilai
1013 Maria Edwards F 53 9798534 Narocivo
1014 Maria Jenkins F 34 9352516 Lomanikoro
1015 Louise Davis F 55 9812126 Nasilai
1016 Sandra Sanders F 29 9369570 Tavuya
1017 Bonnie Roberts F 40 9689234 Nukui
1018 Melissa Harris F 29 9321235 Drekena
1019 Marilyn Parker F 56 9409221 Nukui
1020 Bonnie Lopez F 43 9342939 Nasigatoka
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
I'm trying to remove the 0s but I dont know how to do that. However when I take out the reading for either file it shows the correct output without the 0s
while(!userFile.eof())
{
userFile >> user[index].user_id >> user[index].fname >> user[index].lname >> user[index].gender >> user[index].age >> user[index].phone >> user[index].address;
index++;
}
while(!contactFile.eof())
{
contactFile >> contact[index].user_id >> contact[index].contact_with >> contact[index].contact_start >> contact[index].contact_end >> contact[index].distance;
index++;
}
users(userFile,index,user);
contacts(contactFile,index,contact);
Assuming index starts at zero.
Assuming userFile has 10 lines
Assuming contactFile has 10 lines
when you populate your user array in the while(!userFile.eof()) you increment index to 10... but then when doing the while(!contactFile.eof()) your index is no longer starting at zero... but rather starting where it left off at 10 and continues to 20
you need an additional index...
int uIndex = 0;
int cIndex = 0;
while(!userFile.eof())
{
userFile >> user[uIndex].user_id >> user[uIndex].fname >> user[uIndex].lname >> user[uIndex].gender >> user[uIndex].age >> user[uIndex].phone >> user[uIndex].address;
uIndex++;
}
while(!contactFile.eof())
{
contactFile >> contact[cIndex].user_id >> contact[cIndex].contact_with >> contact[cIndex].contact_start >> contact[cIndex].contact_end >> contact[cIndex].distance;
cIndex++;
}
users(userFile,uIndex,user);
contacts(contactFile,cIndex,contact);
I'm copying a part of my code that tries to save data from a text that is presented line per line. a, b, e, f are strings while the other variables are ints. The problem is that in e it saves nothing and in f saves the part corresponding to e. After this I try to read more data but always saves nothing in e. Please help
.
strong text
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream archivote;
archivote.open(vuelos.txt);
string line,a,b,e,f;
int ca,cb,cc,cd,ce,da,db,dc,dd,de,q;
while(getline(archivote, line)){
getline(archivote,a);
getline(archivote,b);
archivote >> ca;
archivote >> cb;
archivote >> cc;
archivote >> cd;
archivote >> ce;
archivote >> da;
archivote >> db;
archivote >> dc;
archivote >> dd;
archivote >> de;
getline(archivote,e);
getline(archivote,f);
cout << a << '\n' <<b << '\n'<< ca << '\n'<< cb
<< '\n'<< cc << '\n'<< cd << '\n'<< ce << '\n'
<< da << '\n'<< db << '\n'<< dc << '\n'<< dd <<
'\n' << de << '\n'<< e << '\n'<< f;
return 0;
}
}
And the text
Mexico
Puebla
12
12
2000
12
13
12
12
2000
12
22
AeroMexico
1234
Buenos Aires
Panama
02
12
2000
03
12
02
12
2000
05
23
Viva Aerobus
1592
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream fin ("data1.txt");
int ID;
string name;
int test1, test2, test3;
char answer;
cin >> answer;
while (answer = 'Y')
{
fin >> ID;
getline(fin, name);
cout << name << endl;
fin >> test1, test2, test3;
cout << ID << endl;
cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
cin >> answer;
}
}
http://postimg.org/image/fjknavue9/ (Image showing the error)
It showing this error.
For some reason it is just reading the first ID. And then garbage.
This is the TXT file
211692
Ahmed, Marco
66 88 99
240885
ATamimi, Trevone
30 60 90
281393
Choudhury, Jacob
45 55 65
272760
De la Cruz, Edward
79 89 49
199593
Edwards, Faraj
90 56 96
256109
Edwards, Bill
93 94 95
246779
Gallimore, Christian
22 88 66
270081
Lopez, Luis
100 100 100
114757
Mora, Sam
63 78 88
270079
Moses, Samuel
48 95 99
193280
Perez, Albert
97 57 0
252830
Rivas, Jonathan
44 56 76
252830
Robinson, Albert
85 87 89
276895
Miranda, Michael
82 72 62
280515
Robinson, Iris
64 78 91
Program wwill only read the first id, but nothing else, yet it will display whats given, if not garbage. With knowing the solution or understanding, what is going wrong, it can help me in another program that deals with the same logic.
As #Akshat Mahajan mentioned two problems in your code, I fixed and tested them.
One more thing is needed. You should add a line fin.ignore() to ignore the the new line after taking an integer from file.
Here is the working code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream fin ("data1.txt");
int ID;
string name;
int test1, test2, test3;
char answer;
cin >> answer;
while (answer == 'Y')
{
fin >> ID;
fin.ignore();
getline(fin, name);
cout << name << endl;
fin >> test1>> test2>> test3;
cout << ID << endl;
cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
cin >> answer;
}
}
However, you have done some bad practice in your code. Instead of using answer == 'Y' as the condition of while, try something like fin>>ID.
If you choose to use getline for everything, you can change your code a little bit as below.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
ifstream fin ("data1.txt");
int ID;
string name, line;
int test1, test2, test3;
char answer;
cin >> answer;
while (answer == 'Y')
{
getline (fin, line);
ID = stoi(line);
getline(fin, name);
cout << name << endl;
getline(fin, line);
stringstream ss(line);
ss >> test1 >> test2 >> test3;
cout << ID << endl;
cout << test1 << "\t" << test2 << "\t" << test3 << "\t";
cin >> answer;
}
}
I'm a very novice programmer, and I'm trying to make a program that reads a txt file containing the names of 5 students (first names only) as well as four exam scores for each student. I'm trying to read the names into an array called students, then read the scores into 4 separate arrays named test1, test2, test3, test4, then display it from the monitor. The file looks like this:
Steve 78 65 82 73
Shawn 87 90 79 82
Annie 92 90 89 96
Carol 72 65 65 60
Kathy 34 50 45 20
I'm having a very hard time with breaking up the arrays and organizing them. Can someone help me? Please keep in mind I'm very novice, so I don't know a large amount about programming.
This is my code thus far:
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <ctime>
#define over2 "\t\t"
#define over3 "\t\t\t"
#define over4 "\t\t\t\t"
#define down5 "\n\n\n\n\n"
using namespace std;
int main(int argc, char *argv[])
{
ifstream inputFile;
//Constant for max string size
const int SIZE = 5;
//Constant for the scores
string names[SIZE], fileName, line, test1[SIZE], test2[SIZE], test3[SIZE], test4[SIZE];
//input section, user enters their file name
cout << down5 << down5 << over2 << "Please enter your file name: ";
cin >> fileName;
system("CLS");
//open the file containing the responses
inputFile.open(fileName.c_str());
cout << endl;
//kicks you out if file isn't found
if (inputFile)
{
for(int i = 0; i < SIZE; i++)
{
getline(inputFile, line);
names[i] = line;
getline(inputFile, line);
test1[i] = line;
getline(inputFile, line);
test2[i] = line;
getline(inputFile, line);
test3[i] = line;
getline(inputFile, line);
test4[i] = line;
}
inputFile.close();
}
cout << down5 << over3 << "Student\tTest1\tTest2\tTest3\tTest4\n";
cout << over3 << "-------\t-----\t-----\t-----\t-----\n";
for(int i = 0; i < SIZE; i++)
{
cout << over3 << names[i] << endl;
cout << over3 << test1[i] << endl;
cout << over3 << test2[i] << endl;
cout << over3 << test3[i] << endl;
cout << over3 << test4[i] << endl;
}
return 0;
}
Let's look at the structure of the file you're trying to read:
Steve 78 65 82 73
Shawn 87 90 79 82
Annie 92 90 89 96
Carol 72 65 65 60
Kathy 34 50 45 20
The format of the data can be described as follows:
Each line represents a single "record".
Each "record" contains multiple columns.
Columns are separated by whitespace.
You're currently using getline() for every column:
for(int i = 0; i < SIZE; i++)
{
getline(inputFile, line);
names[i] = line;
getline(inputFile, line);
test1[i] = line;
getline(inputFile, line);
test2[i] = line;
getline(inputFile, line);
test3[i] = line;
getline(inputFile, line);
test4[i] = line;
}
...whereas you actually want to read in a single line for each record and split it up:
for (int i = 0; i < SIZE; i++)
{
string line;
size_t start = 0;
// For each line, attempt to read 5 columns:
getline(inputFile, line);
names[i] = get_column(line, start);
test1[i] = get_column(line, start);
test2[i] = get_column(line, start);
test3[i] = get_column(line, start);
test4[i] = get_column(line, start);
}
Here's a modified version of your original code, which splits up each line as described above:
#include <cctype>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
static string get_column(string line, size_t &pos)
{
size_t len = 0;
// Skip any leading whitespace characters.
while (isspace(line.c_str()[pos])) { ++pos; }
// Count the number of non-whitespace characters that follow.
while (!isspace(line.c_str()[pos+len]) && line.c_str()[pos+len]) { ++len; }
// Extract those characters as a new string.
string result = line.substr(pos, len);
// Update the "start" position (for the next time this function is called).
pos += len;
// Return the string.
return result;
}
int main()
{
const int SIZE = 5;
string names[SIZE], test1[SIZE], test2[SIZE], test3[SIZE], test4[SIZE];
// Ask the user to enter a file name.
cout << "Please enter your file name: ";
string fileName;
cin >> fileName;
// Open the file and read the data.
ifstream inputFile(fileName.c_str());
if (!inputFile.is_open()) { return 0; }
for (int i = 0; i < SIZE; i++)
{
string line;
size_t start = 0;
// For each line, attempt to read 5 columns:
getline(inputFile, line);
names[i] = get_column(line, start);
test1[i] = get_column(line, start);
test2[i] = get_column(line, start);
test3[i] = get_column(line, start);
test4[i] = get_column(line, start);
}
inputFile.close();
// Display the data.
cout << "Student\tTest1\tTest2\tTest3\tTest4" << endl;
cout << "-------\t-----\t-----\t-----\t-----" << endl;
for(int i = 0; i < SIZE; i++)
{
cout << names[i] << "\t";
cout << test1[i] << "\t";
cout << test2[i] << "\t";
cout << test3[i] << "\t";
cout << test4[i] << endl;
}
}
Running the program produces the following output:
Please enter your file name: textfile.txt
Student Test1 Test2 Test3 Test4
------- ----- ----- ----- -----
Steve 78 65 82 73
Shawn 87 90 79 82
Annie 92 90 89 96
Carol 72 65 65 60
Kathy 34 50 45 20
Note that the get_column() function handles multiple spaces or too-short lines, so that this file:
Steve 78 65 82 73
Shawn 87 90
Annie 92 90 89 96
Carol 72
Kathy 34 50 45 20
...produces the following output:
Please enter your file name: textfile.txt
Student Test1 Test2 Test3 Test4
------- ----- ----- ----- -----
Steve 78 65 82 73
Shawn 87 90
Annie 92 90 89 96
Carol 72
Kathy 34 50 45 20
The previous answer is overthinking the problem.
You can use your input file stream to retrieve 'formatted input' (that is, input you know to be in a format such as 'string' then 'int', 'int', 'int', 'int') with the >> operator.
string name;
int score[4];
ifstream mf;
mf.open("score.txt");
// Get name string.
mf >> name;
// Get four score values into an array.
mf >> score[0] >> score[1] >> score[2] >> score[3];
And then:
cout << name;
cout << score[0];
cout << score[1];
cout << score[2];
cout << score[3];
I've never posted here before but I'm really stuck so I thought i'd give it a try. I've been working on this code for a while, The aim is to input a few students with their marks and to output them into tables with averages and totals. I was given a file like this:
15
Albert Einstein 52 67 63
Steve Abrew 90 86 90 93
David Nagasake 100 85 93 89
Mike Black 81 87 81 85
Andrew Van Den 90 82 95 87
Joanne Dong Nguyen 84 80 95 91
Chris Walljasper 86 100 96 89
Fred Albert 70 68
Dennis Dudley 74 79 77 81
Leo Rice 95
Fred Flintstone 73 81 78 74
Frances Dupre 82 76 79
Dave Light 89 76 91 83
Hua Tran Du 91 81 87 94
Sarah Trapp 83 98
my problem is that when I am inputting the names the program crashes after Fred Flinstone, I know its not a problem with the formatting of the next name (Frances Dupre) because when i moved him up the list it read it fine.
I have located where the program is crashing with 'cerr' outputting at different stages of the read process and it crashes when it is trying to read in Frances's marks.
a1main.cpp
#include <iostream>
#include "student.h"
using namespace std;
int main()
{
int numStds;
cin >> numStds;
cerr << endl << "Num Stds: " << numStds << endl;
Student std[numStds+1];
for(int i = 0; i <= numStds; i++)
{
std[i].readData();
std[i].printStudent();
}
// delete [] std;
return 0;
}
student.h
#include <iostream>
using namespace std;
class Student {
private:
char* name;
int mark[4];
int num;
public:
Student();
~Student();
void readData();
void printStudent();
float getTotal();
float getAverage();
};
student.cpp
#include <iostream>
#include <cstring>
#include <cctype>
#include "student.h"
using namespace std;
Student::Student()
{
name = new char;
mark[0] = 0;
mark[1] = 0;
mark[2] = 0;
mark[3] = 0;
num = 0;
}
Student::~Student()
{
// Doesn't work?
// delete name;
}
void Student::readData()
{
int l = 0;
// Reading the Name
cin >> name; // Read in the first name
l = strlen(name); // get the strlength
name[l] = ' '; // Putting a space between the first and last name
cin >> &name[l+1]; // Read in the last name
cerr << endl << "I have read the name!" << endl;
// Checking if there is a third name
if(cin.peek() == ' ')
cin >> ws; // checking and navigating past the whitespace
char next = cin.peek();
if( isalpha(next) ) // Checking whether the next cin is a char
{
l = 0;
l = strlen(name);
name[l] = ' ';
cin >> &name[l+1];
}
cerr << "I've checked for a third name!" << endl;
// Reading in the marks
for(int i = 0; i < 4; i++)
{
// Checks if the next cin is a newline
if (cin.peek() == '\n')
break;
cin >> mark[i];
}
cerr << "I've read in the marks!" << endl;
//cerr << endl << "I have read " << name << "'s marks!" << endl << endl;
for(int m = 0; m < 4; m++)
{
if(mark[m] != 0)
{
num++;
}
}
cerr << "I've incremented num!" << endl << endl;
}
// Function for error checking
void Student::printStudent()
{
cout << endl << "Student Name: " << name << endl;
cout << "Mark 1: " << mark[0] << endl;
cout << "Mark 2: " << mark[1] << endl;
cout << "Mark 3: " << mark[2] << endl;
cout << "Mark 4: " << mark[3] << endl;
cout << "num marks: " << num << endl << endl;
}
float Student::getTotal()
{}
float Student::getAverage()
{}
Can anyone see what i'm doing wrong? thanks :)
You're never allocating memory to store the student names.
In your Student constructor, add this code:
name = new char[100]; // allows names up to 100 characters long
and uncomment this line in the destructor:
delete[] name;
You could also make the code more sophisticated and robust by measuring the name length and allocating the correct size, or use std::string as suggested below.