Search code examples
c++randomfstream

C++ adding a carriage return at beginning of string when reading file


I have two questions:

1) Why is my code adding a carriage return at the beggining of the selected_line string?
2) Do you think the algorithm I'm using to return a random line from the file is good enough and won't cause any problems?

A sample file is:

line
number one
#
line number two

My code:

int main()
{
    srand(time(0));
    ifstream read("myfile.dat");
    string line;
    string selected_line;
    int nlines = 0;
    while(getline(read, line, '#')) {
        if((rand() % ++nlines) == 0)
            selected_line = line;
    }
    // this is adding a \n at the beginning of the string
    cout << selected_line << endl; 
}

EDIT: OK, what some of you suggested makes a lot of sense. The string is probably being read as "\nmystring". So I guess my question now is, how would i remove the first \n from the string?


Solution

  • What you probably want is something like this:

    std::vector<std::string> allParagraphs;
    std::string currentParagraph;
    
    while (std::getline(read, line)) {        
        if (line == "#") { // modify this condition, if needed
            // paragraph ended, store to vector
            allParagraphs.push_back(currentParagraph);
            currentParagraph = "";
        else {
            // paragraph continues...
            if (!currentParagraph.empty()) {
                currentParagraph += "\n";
            }
            currentParagraph += line;
        }          
    }
    
    // store the last paragraph, as well
    // (in case it was not terminated by #)
    if (!currentParagraph.empty()) {
        allParagraphs.push_back(currentParagraph);
    }
    
    // this is not extremely random, but will get you started
    size_t selectedIndex = rand() % allParagraphs.size();
    
    std::string selectedParagraph = allParagraphs[selectedIndex];
    

    For better randomness, you could opt for this instead:

    size_t selectedIndex 
        = rand() / (double) (RAND_MAX + 1) * allParagraphs.size();
    

    This is because the least significant bits returned by rand() tend to behave not so randomly at all.