0

I am trying to read a file with separate columns and including each word of a column in an array. Some of them are numeral, other literals. For the literals, I am always getting and error of type conversion. Any idea? Here follows the code:

#include <iostream>
#include <fstream>
#include <cmath>

int main ()
{
    string line; 
    int a=100;
    ifstream data;
    data.open("filename.txt");
    getline(data,line);

    int number[a];
    const char *at[3][a];
    const char *rt[3][a];
    int rn[a];

    for (int j=0;j<a;j++)
    {
        number[j] = stoi(line.substr(6,6));
        at[j] = line.substr(13,2);
        rt[j] = line.substr(13,2);
        rn[j] = stoi(line.substr(22,4));
        getline(pdb,line);
    } 
    return 0;
}

I appreciate any help!

4
  • Please correctly indent your code, that should be a better starting point! Commented Jan 2, 2016 at 22:13
  • What's the structure of your file? Commented Jan 2, 2016 at 22:16
  • substr returns a std::string. You cannot assign that to an array of char pointers (or whatever those variables are supposed to be). Commented Jan 2, 2016 at 22:17
  • Why aren't you using std::string and std::vector? Commented Jan 2, 2016 at 22:21

1 Answer 1

3

A std::string is not a char const*. Use array item type std::string instead of const char*. You need to include the <string> header. Also include <vector>, and use std::vector instead of those raw arrays. Do note that the declaration int number[a] is non-standard, it uses a g++ language extension (namely C99 variable length arrays). Using std::vector you therefore also get more portable code.


E.g., instead of

int number[a];    // Non-standard

write

vector<int> number( a );

There are more details that could be mentioned, but it's unclear what's by design here and what's due to misunderstandings. So, if there's still a problem after making the transition to std::string and std::vector, I suggest making a new question instead of amending this one.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot Cheers! My biggest problem is to find a way to iteratively generate an array of words collected by reading a specific column. After declaring a string array (instead of a char array), how do I add new words to this string array? Should I declare it as "string at[a];"?
Like vector<string> at(a). Except it could be a good idea to change the name to something more self-describing. And also because std::vector has a member function named at, so use of that name could be confusing.
Solved! Thanks again Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.