1

I have a text file in which the data is stored in following format:-

aabb:aabb aacc:aacc aadd:aadd bbdd:bbdd bbaa:bbaa 

I am reading from the file line by line and trying to separate the words on either side of ':'. I am taking each line into a string line. I am assigning the word left to ':', char by char in the string w and the word right to ':', char by char to string m. But the problem is the the string w and m become empty after both the loops are executed. Why are string w and m empty?

int flag; string line, w, m; ifstream fin; fin.open("files/file2.txt",ios::in); if (fin.is_open()) { while (getline(fin,line)) { for (int i=0; i<line.length(); i++) { if (line[i] == ':') { flag = i+1; break; } else w[i] = line[i]; } for(int i=flag,k=1; i<line.length(); i++,k++) { m[k] = line[i]; } cout<<w<<'\n'; cout<<m<<'\n'; } fin.close(); } 

Thank you for your help.

2
  • why are string w and m empty? Commented Jan 12, 2018 at 18:58
  • 1
    Try w += line[i]; and m += line[i]; Commented Jan 12, 2018 at 18:58

1 Answer 1

2

The problem with your code is that you are assigning characters to positions of m and w that do not exist yet: both strings are initially empty, so applying [] to them causes undefined behavior.

Since you are adding characters to the end of your strings, use append instead of []:

w.append(1, line[i]); ... m.append(1, line[i]); 

or +=:

w += line[i]; ... m += line[i]; 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.