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.
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)
vector<string> CategoryWithoutHashTags;
string tester = "#hello junk #world something #cool";
char *pch;
char *str;
str = new char [tester.size()+1];
strcpy(str, tester.c_str());
pch = strtok(str,"#");
while(pch!=NULL)
{
CategoryWithoutHashTags.push_back(pch);
pch=strtok(NULL,"#");
}
cout<<CategoryWithoutHashTags[0]<<endl;
I want to write a program which involves storing all the hash tags words in a vector of strings. The above program stores "hello junk" in the first index rather than "hello". What changes can i make to the program to make it do so?
If you are set on using strtok, you should at the very least use its re-entrant version strtok_r. Then, you should change the code to split at spaces, not at hash marks. This would give you the tokens. Finally, in the loop you would need to look for the first character to be the hash mark, adding the item to the list if it's there, and disregarding the item when the hash mark is not there.
An even better approach would be using a string stream: put your string into it, read tokens one by one, and discard ones with no hash mark.
Here is how you can do it with very little code using C++11's lambdas:
stringstream iss("#hello junk #world something #cool");
istream_iterator<string> eos;
istream_iterator<string> iit(iss);
vector<string> res;
back_insert_iterator< vector<string> > back_ins(res);
copy_if(iit, eos, back_ins, [](const string s) { return s[0] == '#'; } );
Demo on ideone.
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'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.
I have several C++ strings with some words. I need to get the first word from every string. Then I have to put all of them into a char array. How can I do it?
Here is one way of doing it...
// SO2913562.cpp
//
#include <iostream>
#include <sstream>
using namespace std;
void getHeadWords(const char *input[]
, unsigned numStrings
, char *outBuf
, unsigned outBufSize)
{
string outStr = "";
for(unsigned i = 0; i<numStrings; i++)
{
stringstream ss(stringstream::in|stringstream::out);
ss<<input[i];
string word;
ss>>word;
outStr += word;
if(i < numStrings-1)
outStr += " ";
}
if(outBufSize < outStr.size() + 1)//Accomodate the null terminator.
//strncpy omits the null terminator if outStr is of the exact same
//length as outBufSize
throw out_of_range("Output buffer too small");
strncpy(outBuf, outStr.c_str(), outBufSize);
}
int main ()
{
const char *lines[] = {
"first sentence"
, "second sentence"
, "third sentence"
};
char outBuf[1024];
getHeadWords(lines, _countof(lines), outBuf, sizeof(outBuf));
cout<<outBuf<<endl;
return 0;
}
But note the above code has marginal error checking and may have security flaws. And needless to say my C++ is a bit rusty. Cheers.
I'll assume it's homework, so here is a general description:
First, you need to allocate enough space in your char array. In homework, you are usually told the maximum size. That maximum has to be enough for all the first words.
Now, you need to have an index for the insertion point in that array. Start it at zero.
Now go over your strings in order. In each, move an index forward from 0 until you see a \0 or a space (or other delimiter. Insert the character at the insertion point in the result array and increase that index by 1.
If you have encountered a space or a \0, you've found your first word. If you were on the last string, insert a \0 at the insertion point and you're done. If not, insert a space and move to the next string.
what compiler are you using?
converting to a chararray is the first thing to look for.
after done that, you can easily step through your array (and look for spaces)
something like this:
while (oldarray[i++] != ' ')
yournewarray[j++];
i think you gotta figure out the rest yourself, since this looks like some homework for school :)
Assuming this is homework, and that when you say "strings" you mean simple null-delimited arrays of char (and not std::string):
define your strings
define your resulting char array
for each string
find the offset of the first char that is not in the first word
append that many bytes of the string to the result array
If this is not homework, give us a little code to start with and we'll fill in the blanks.