I have two string vectors readData and commaSep. I want to read from vector readData and whenever I encounter a comma (,) I want to insert that data into commaSep without the comma. In my program readData has values like "xyz,22,pqr". My getline statement is wrong so suggest me something.
vector<string> readData; // has string values with ',' separation
vector<string> commaSep; // insert them in this vector
string temp;
for (int i = 0; i < readData.size(); i++) {
getline(readData[i], temp, ',');
commaSep.push_back({temp});
getline(readData[i], temp, ',');
commaSep.push_back({temp});
getline(readData[i], temp, '\n');
commaSep.push_back({temp});
}
Related
The real file I read is about 15.000 kBs. Thus I am not sure whether this is the best way of storing such a data structure.
Here is the code.
string line;
ifstream File;
vector<vector<string>> v;
string filename = "meddra.txt";
File.open(filename);
if (File.is_open()) {
while (getline(File, line)) {
stringstream ss(line);
vector<string> row;
while (getline(ss, line, ',')) {
row.push_back(line);
}
v.push_back(row);
}
}
And here is sample text file:
CID100000085,CID000010917,C0000729,Abdominal cramps
CID100000085,CID000010917,C0000737,Abdominal pain
CID100000085,CID000010917,C0002418,Amblyopia
CID100000085,CID000010917,C0002871,Anaemia
CID100000085,CID000010917,C0003123,Anorexia
Thank you for contribution.
You are modifying an empty vector
vector<vector<string>> v;
v[c][j].push_back(line);
Instead you should do v.push_back with a vector<string>
You have defined a vector of vectors like this:
vector<vector<string> v
then if you analyze the following instruction:
v[c][j].push_back(line);
then you are calling a push_back(line) method into a string.
v is a vector holding vectors of strings
v[i] is a vector of strings at index i
v[i][j] is a string at index j of the vector at index i
that is the reason of the error
You need to use v[c][j] = line; instead of v[c][j].push_back(line);. v[c][j] returns a mutable ref of type string. However string does not have push_back() method.
And as v[c][j] is a mutable ref it can be assigned to a new value.
I basically have a txt file that looks like this...
High Score: 50
Player Name: Sam
Number Of Kills: 5
Map
Time
I want to store everything before the : or whitespace after Map and Time into one array and everything after in another. For both Map and Time, there is nothing after and so I want to store the whitespace as null.
So far, I have managed to read and store all this information into a temp array. However, it is separating that I am having trouble with. This is my code:
istream operator >> (istream &is, Player &player)
{
char **temp;
char **tempNew;
char lineInfo[200]
temp = new char*[5];
tempNew = new char*[5];
for (int i=0; i<5; i++)
{
temp[i] = new char[200];
is.getline(lineInfo, sizeof(lineInfo));
int length = strlen(lineInfo);
for (int z=0; z < length; z++)
{
if(lineInfo[z] == '= ' ){ //HOW DO I CHECK IF THERE IS NOTHING AFTER THE LAST CHAR
lineInfo [length - (z+1)] = lineInfo [length];
cout << lineInfo << endl;
strncpy(temp[i], lineInfo, sizeof(lineInfo));
}
else{
tempNew[i] = new char[200];
strncpy(tempNew[i], lineInfo, sizeof(lineInfo));
}
}
}
If what you need is to find ':'
#include <cstring>
and just
auto occurance = strstr(string, substring);
Documentation here.
if occurance is not a null ptr, then see if occurance is at the end of the line from get line. If not, your value is everything after that :
Much easier with std::string.
// Read high score
int high_score;
my_text_file.ignore(10000, ':');
cin >> high_score;
// Read player name
std::string player_name;
my_text_file.ignore(10000, ':');
std::getline(my_text_file, player_name);
// Remove spaces at beginning of string
std::string::size_type end_position;
end_position = player_name.find_first_not_of(" \t");
if (end_position != std::string::npos)
{
player_name.erase(0, end_position - 1);
}
// Read kills
unsigned int number_of_kills = 0;
my_text_file.ignore(':');
cin >> number_of_kills;
// Read "Map" line
my_text_file.ignore(10000, '\n');
std::string map_line_text;
std::getline(my_text_file, map_line_text);
// Read "Text" line
std::string text_line;
std::getline(my_text_file, text_line);
If you insist on using C-style strings (arrays of char), you will have to use more complex and less safe functionality. Look up the following functions:
fscanf, strchr, strcpy, sscanf
This question already has answers here:
Reading in a specific column of data from a text file in C
(4 answers)
Why does reading a record struct fields from std::istream fail, and how can I fix it?
(9 answers)
Closed 8 years ago.
I have a file which stores data in the following format (this is just a small sample) :
AD,Andorra,AN,AD,AND,20.00,Andorra la Vella,Europe,Euro,EUR,67627.00
AE,United Arab Emirates,AE,AE,ARE,784.00,Abu Dhabi,Middle East,UAE Dirham,AED,2407460.00
AF,Afghanistan,AF,AF,AFG,4.00,Kabul,Asia,Afghani,AFA,26813057.00
AG,Antigua and Barbuda,AC,AG,ATG,28.00,Saint John's,Central America and the Caribbean,East Caribbean Dollar,XCD,66970.00
AI,Anguilla,AV,AI,AIA,660.00,The Valley,Central America and the Caribbean,East Caribbean Dollar,XCD,12132.00
I want to store the second field of each line such that my array contains only the country names like so:
string countryArray[] = {"Andorra,United Arab Emirates", "Afghanistan", "Antigua and Barbuda", "Anguilla"}
But each time I run my code, a segmentation fault occurs. Here is my code :
countryArray[256];
if (myfile)
{
while (getline(myfile,line))
{
std::string s = line;
std::string delimiter = ",";
size_t pos = 0;
std::string token;
short loop=0;
while ((pos = s.find(delimiter)) != std::string::npos)
{
token = s.substr(0, pos);
s.erase(0, pos + delimiter.length());
if (loop < 2)
{
loop++;
}
else
{
loop+=11;
countryArray[count] = token;
count++;
}
}
}
}
Consider using std::istringstream. Something like:
while(getline(myfile, line))
{
std::istringstream iss(line);
std::string data;
getline(iss, data, ','); // get first column into data
getline(iss, data, ','); // get second column into data
countryArray[count] = data;
++count;
}
What std::istringstream does is allow you to treat a std::string like an input stream just like a regular file.
The you can use getline(iss, data, ',') which reads from the stream up to the next comma ',' and stores it in std::string data.
EDIT:
Also consider using std::vector rather than an array.
Your segfault is most likely the result of not initializing count, and then using that variable as the index into the countryArray array. Thus you could be easily overrunning the bounds of the array since the value in count is undefined.
I am trying to set a variable to the value of an element of a 2D array. This should be easy, but whenever I write it I get 0 in the variable. I read in a file to put in the array elements manually, which might be causing the problem, but I am not sure what's wrong.
Here is my code:
int main(){
//declaring all the variables
vector < vector <double> > data; // vector of vectors to hold the data.
int z=0;
int z1,z2;
//open the input file as an input file stream (ifstream)
ifstream dataFile;
dataFile.open( "GBplaces.csv" );
//if the file is open...
if (dataFile.is_open()) {
// and while it's not the end of the file...
while (!dataFile.eof() ){
z++;
if (z==1){
string aLine;
getline ( dataFile, aLine );
printf ("place, type, population, lattitude, longitude \n\n");
}
else if(z==102){
string aLine;
getline ( dataFile, aLine );
}
else {
//read in a line of the file and put the ontents into the arays.
string aLine; // hold the read in line
getline ( dataFile, aLine ); //reads line from dataFile to aLine
//split up the string aLine based on where the comma is
int comma;
int nextCom=0;
//comma_pos = aLine.find(',',0); //finds where the comma is, starting from the begining ie 0
string xst, yst, zst; //temp variables for column
vector <double> temp; // tempory vector for the points
double xt, yt, zt;
comma = aLine.find(',',0); //find first position of comma
xst = aLine.substr(0,comma); // extracts string subvalue
temp.push_back(atof(xst.c_str())); //add value to end of temporary vector
comma += 1; // add 1 to the comma position count
while (aLine.find(',',comma) != -1) {
// find middle values
if(aLine==""){}
else{
nextCom = aLine.find(',',comma);
yst = aLine.substr(comma, nextCom - comma);
temp.push_back(atof(yst.c_str())); //convert string into double and add it to the end of the vector
comma = nextCom + 1;
}
}
// same calculations as in the loop but for the last value after the comma
zst = aLine.substr(nextCom + 1, aLine.length());
temp.push_back(atof(zst.c_str()));
// push temporary vector onto data vector
data.push_back(temp);
}
}
}
z = data[3][3].
When I run the program I get z=0, although when I print the table, the element is 51.26.
Update:
Found the error:
int z=0;
int z1,z2;
z1,z2 should be doubles instead of integers. This was messing up the rest of the number
I want to be able to read a full line into a character array using a function.
example input text is:
Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly
However, im not sure how to read a full line of characters into the array. I know the delimiter for >> is whitespace, but I'm not sure if I change that delimiter to '\n' if it'd work?
void buildList(char (*array)[25], ifstream& inputFile){
string line;
for (int i = 0; i < 5; i++)
getline(inputFile, line);
array[i] = line.c_str();
}
Currently this only reads either a last name or first name into my input instead of the whole line. I'm not sure how I can go about changing this. Thanks.
First, you definitely want to use std::string here. Once you
do that, you can use std::getline:
std::vector<std::string>
buildList( istream& input )
{
std::vector<std::string> results;
std::string line
while ( std::getline( input, line ) ) {
results.push_back( line );
}
}
This will make for much simpler and more robust code.
If you have to use such a broken interface, there is a member
function getline:
for ( int i = 0; i != 5; ++ i ) {
input.getline( array[i], maxLength );
}
Also: a function should never take an std::ifstream& as
argument (unless it is going to open or close the file). An
std::istream& should be used.
Use this-
void buildList(char (*array)[25], ifstream& inputFile){
for (int i = 0; i < 5; i++)
std::inputFile.getline(array[i],50);
}
The second parameter of getline is the maximum number of characters to write to the character array.