Thread: string issue

  1. #1
    Registered User
    Join Date
    Apr 2004
    Posts
    10

    string issue

    I programming in C++ on linux. I am trying to read 1 line of data from an input file and store it in a string. There are no spaces anywhere on the line. Because I had issues using a string and getline, I used a char array to store line when it is read in and then I created a new string by passing the char array into the string's constructor. The data in the string is grouped in sets of 3 characters, so I get the length of the string using str.length() and divide the length by 3 to get the number of sets in the string. For testing purposes, I am writing length of the string and the number of character sets to stdout. When I test with a file that has 16 character sets, I get the correct output. But when I test with a file that has 49 character sets, I am getting the wrong output. Instead of getting a string length of 147 and 49 sets, I am getting a string length of 161 and 53 sets. Somehow the string length is being returned as larger than it should be. Does anyone have any suggestions as to how to fix this problem? Is there a way that I can use a c++ string instead of a char array to read the line from the input file? Thanks.

  2. #2
    Registered User
    Join Date
    Apr 2004
    Posts
    10
    Nevermind, I'm retarded. The 3rd character in each set is an integer. And that integer can be greater than 9. Therefore, I can't just assume that each set is 3 characters.

  3. #3
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    and dont forget when you are using arrays of char's you must have 1 extra space for the '\0' at the end!

  4. #4
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    A different version of getline works with strings. You have to include <string> and call the global getline function with the stream as the first parameter. For example:

    std::getline(inputStream, dataString);

  5. #5
    Registered User
    Join Date
    Jul 2003
    Posts
    26
    Code:
    using namespace std;
    
    string mine;
    
    ifstream myFile("file.txt", ios::in);
    
    getline(myFile, mine, '\n');
    --LiKWiD
    Becoming un-noobified one day at a time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM