I'm trying to store strings that I read from a file in a std::vector but I'm getting a weird error...
So I have the container:
std::vector<std::string> m_Strings;
Then I read the string from a stream:
ifstream inStream;
char word[100];
//[...]
inStream >> word;
m_Strings.push_back(word);
Even though the vector is empty, when I insert the first string the vector resizes to hold 8 strings, the string at index 0 containing random characters, at index 1 containing the correct word, and the other indices containing invalid pointers...
Any idea of what might cause this?
EDIT: In this case I'm reading the string "DIRECTIONAL_LIGHT" so it fits in the char word[100]
Just changed char word[100]; to std::string word; and the error disappeared.
Related
I have been trying a while to do that but sadly i couldn't and it interests me to do such a thing, i always wanted to have a array of strings! Let's say i have a loop where i gather strings -
std::string input;
std::vector<std::string> svec;
int i = 0;
while (std::cin >> input) {
svec[i++] = input;
}
I'm unable to do
svec[i++] = input;
and I want to find a way to allocate the vector without giving it exact size( unknown amount of strings), how do i do that?
Before accessing some index, this element needs to exist.
To insert new elements, use push_back
svec.push_back(input);
See http://en.cppreference.com/w/cpp/container/vector
You want
svec.push_back(input);
(There's good documentation here: http://en.cppreference.com/w/cpp/container/vector/push_back)
I want to read in lines from a text file into a 2-d char array but without the newline character.
Example of .txt:
TCAGC
GTAGA
AGCAG
ATGTC
ATGCA
ACAGA
CTCGA
GCGAC
CGAGC
GCTAG
...
So far, I have:
ifstream infile;
infile.open("../barcode information.txt");
string samp;
getline(infile,samp,',');
BARCLGTH = samp.length();
NUMSUBJ=1;
while(!infile.eof())
{
getline(infile,samp,',');
NUMSUBJ++;
}
infile.close(); //I read the file the first time to determine how many sequences
//there are in total and the length of each sequence to determine
//the dimensions of my array. Not sure if there is a better way?
ifstream file2;
file2.open("../barcode information.txt");
char store[NUMSUBJ][BARCLGTH+1];
for(int i=0;i<NUMSUBJ;i++)
{
for(int j=0;j<BARCLGTH+1;j++)
{
store[i][j] = file2.get();
}
}
However, I do not know how to ignore the newline character. I want the array to be indexed so that I can access a sequence with the first index and then a specific char within that sequence with the second index; i.e. store[0][0] would give me 'T', but I do not want store[0][5] to give me '\n'.
Also, as an aside, store[0][6], which I think should be out of bounds since BARCLGTH is 5, returns 'G',store[0][7] returns 'T',store[0][8] returns 'A', etc. These are the chars from the next line. Alternatively, store[1][0],store[1][1], and store[1][2] also return the same values. Why does the first set return values, shouldn't they be out of bounds?
As you're coding in C++, you could do like this instead:
std::vector<std::string> barcodes;
std::ifstream infile("../barcode information.txt");
std::string line;
while (std::getline(infile, line))
barcodes.push_back(line);
infile.close();
After this the vector barcodes contains all the contents from the file. No need for arrays, and no need to count the number of lines.
And as both vectors and strings can be indexed like arrays, you can use syntax such as barcodes[2][0] to get the first character of the third entry.
I have tried alot of suggestion solutions to this problem with no success.
I have a const char array, of length 1000, called english_line which containing words seperated by whitespace. This array is passed into a function. This function must be used to implemented the solution as per our assignment brief.
I want to copy the contents of that array, one word at a time into another 2D array, temp_eng_word
char temp_eng_word[2000][50];
int j;
string line = english_line;
string word;
istringstream iss(line, istringstream::in);
while (iss >> word)
{
for (j=0;j<=2000;j++)
{
strcpy(temp_eng_word[j],word);
}
}
`
When I run this, I get the error:
cannot convert 'std::string* *{aka std::basic_string(char)}' to 'const char*' for argument '2' to 'char* strcpy(char*, const char*)'
I have spent the best part of a day just trying to do this problem; obviously I am a relative novice at this.
Any tips or suggestions would be greatly appreciated :)
Use word.c_str() to get a const char* out of the std::string
Also, I don't understand the point of your nested for loop, you may want to do something like this instead (using strncpy to copy a maximum of 49 char with zero-padding if needed, and ensure the last char of the string is always zero) :
istringstream iss(line, istringstream::in);
int nWord = 0;
while( (nWord < 2000) && (iss >> word) )
{
strncpy(temp_eng_word[nWord], word.c_str(), 49);
temp_eng_word[nWord][49] = '\0'; /* if it's not already zero-allocated */
++nWord;
}
Note that it would be simpler to use std::vector<std::string> to store your words :
vector<string> words;
istringstream iss(line, istringstream::in);
while(iss >> word)
{
words.push_back(word);
}
Which could be done without a loop using std::copy :
copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(words));
1) Loop count wrong (You should correct your array knowledge)
2) string::c_str() to convert std::string to char*
Note the difference between string and char array. Char array is a simple structure of basic data type and string is actually a class having more complicated structure. That's why you need to use c_str() function of the string to get the content as char array (a.k.a C-string).
You should also notice that c_str() adds null termination (additional character '\0') in the end of its output array.
You can use string instead of that array temp_eng_word. Like,
std::string temp_eng_word;
Hope that will fix your problem. And the loop is not correct. Please check that, as you are using two dimensional array.
I've the need of read a txt file that is structured in this way
0,2,P,B
1,3,K,W
4,6,N,B
etc.
Now I need to read in an array like arr[X][4]
The problem is that I don't know the number of lines inside this file.
In addition I'd need 2 integers and 2 char from it...
I think I can read it with this sample of code
ifstream f("file.txt");
while(f.good()) {
getline(f, bu[a], ',');
}
obviusly this only shows you what I think I can use....but I'm open to any advice
thx in advance and sry for my eng
Define a simple struct to represent a single line in the file and use a vector of those structs. Using a vector avoids having to manage dynamic allocation explicitly and will grow as required.
For example:
struct my_line
{
int first_number;
int second_number;
char first_char;
char second_char;
// Default copy constructor and assignment operator
// are correct.
};
std::vector<my_line> lines_from_file;
Read the lines in full and then split them as the posted code would allow 5 comma separated fields on a line for example, when only 4 is expected:
std::string line;
while (std::getline(f, line))
{
// Process 'line' and construct a new 'my_line' instance
// if 'line' was in a valid format.
struct my_line current_line;
// There are several options for reading formatted text:
// - std::sscanf()
// - boost::split()
// - istringstream
//
if (4 == std::sscanf(line.c_str(),
"%d,%d,%c,%c",
¤t_line.first_number,
¤t_line.second_number,
¤t_line.first_char,
¤t_line.second_char))
{
// Append.
lines_from_file.push_back(current_line);
}
}
What I've been trying to do, is read a line from stdin and split it, by using whitespace as seperators.
Let's say I have this as input:
2
1 2
3 4
The first line gives me the amount of lines I'd like to read, they're all lines with integers seperated by an unknown amount of whitespace (i.e. could be 1 space, but it could also be 10 spaces).
The thing I've been trying to do is reading those lines into dynamically sized arrays of integers.
This was extremely easy in Python:
foo = raw_input()
array = foo.split()
or even shorter:
foo = raw_input().split()
However, because of the circumstances, I have to learn the beauty of C++.
So I tried to create something akin to the above Python code:
#include <iostream>
using namespace std;
int lines;
int *array;
int main() {
cin >> lines;
for (int line = 0; line < lines; line++) {
// Something.
}
}
I don't seem to know a way to split the line of input. I know that std::cin reads until it reaches a whitespace. However, I can't seem to think of something to count the amount of numbers on the line...
A little nudge into the right direction would be appreciated, thanks.
so given all you wanted is a nudge, here are a couple of hints..
std::getline() - allows you to read from a stream into a std::string.
You can then construct a std::istringstream using this string which you've just read in. Then use this stream to read your ints
for example:
std::string line;
if(std::getline(std::cin, line))
{
std::istringstream str(line);
int lc;
if (str >> lc) // now you have the line count..
{
// now use the same technique above
}
}
oh and for your "dynamically sized array", you need to look at std::vector<>
In C++ you can access characters in a string with [], just as if that string were an array. I suggest you read a line from cin into a string, iterate over the string with a for loop and check each character to see whether it is whitespace. Whenever you find a non-whitespace character, store it in your array.