open .txt, read line by line, store into a string variable

I am attempting to take a .txt file, and read each line in to a string. the file consists of a character, followed by a space, and then a name. the character defines a rule for the linked list I am creating:

a Bobby - 'a' means I need to insert this. Next line
r Johnny - and so on..

I am in college at 30 trying to learn this, and I am stuck now.

I have some code, but I am not sure I understand it well enough to know if I am doing this correctly so I have left my thoughts, and I would love to know if I am wrong. This is obviously impartial code, because everything I try is wrong!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<fstream>
#include <string>
#include <iostream>

using namespace std;
  int main() {

	string name;
	char action;

	ifstream myfile;

	myfile.open("test.txt");
	
	if (myfile.is_open()) {

		string line;

		while (getline(myfile, line)) {

			//store line into variable
			//remove first character to pass to function
			//remove the first letter and the space to store in name

			
		}
	}
So far it looks OK. If your input is guaranteed to be correct you can process line like this.
action = line [0];
name = line.substr(2);
Last edited on
seeplus--I appreciate that. That was my first post and I realize I didnt include code, or information so I made a new post. That being said, some of that stuff has yet to be discussed in our course, and I am worried that if I do something we have yet to go over, I will be marked down. I have another 24 hours before it is due so worst comes to worst, I will give your example a try. Thank you so much!
You should have added the code and assignment info as a new posting to your original topic post instead of creating a new topic.

Just a minor 'netiquette quibble. :)

In the future, if you post code and then make changes to your code after getting advice PLEASE don't alter the original code, add a new post with the updated code/output.

Your question might help others with similar questions, so seeing the progression is useful, and doesn't make the follow-up replies look "wrong."

And THANK YOU for using code tags! They really are helpful for reading and discussing code, :D
Last edited on
Topic archived. No new replies allowed.