basic file I/O string issues

This is a class project. I am using file I/O to read a file for data. It reads the file but when I cout the string it displays the \n instead of a new line. how can i fix this.

example of what I want:
story text some more text
more text
option text
more
more

example of what i get:
story text some more text \n more text
option text \n more \n more \n

Thanks ZeroDragon

[file]
story text some more text \n more text
option text \n more \n more \n
[/file]
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
  void display()
{
	
	string story;
	string options;

	//file I/O
	//1 create file stream
	ifstream page;
	
	//2 open file
	page.open("..//Story//page0");
	
	//3 check if file open
	if(!page.is_open())
		cout<<"Error file not open"<<endl;
	
	//4 read file
	getline(page, story);
	getline(page, options); 
	//5 close file
	page.close();
	
	//quick cout test
	cout<<story<<endl;
	cout<<options<<endl;
}
Last edited on
IF the file contains:
story text some more text \n more text
option text \n more \n more \n

THEN you have text that happens to contain characters '\' and 'n' and there is nothing special in them.

You could replace each occurrence of word "\n" in the strings with actual newline characters. That might be an intentional subtask of the project.
correct me if i am wrong but i thought my file i/o code done this:
line 19 story="story text some more text \n more text";
line 20 options="option text \n more \n more \n";

so how is that any different from the following code that works?
I really want and need to understand how they are different.

1
2
3
4
5
6
void main()
{
	string test="this is line one \nthis is a new line";
	cout<<test;
}

[display]
this is line one
this is a new line
[/display]

so for some reason they are not special. I need to make a sub-task that finds the chars "/" "n" together and replaces them with the actual newline character. BTW what is the newline character I will be using?? I thought it was /n?

also any ideas on how to go about this if the /n is attached to the word as in string test with "\nthis"? with this example i cant just look for the word "/n".

Thanks
If you're in an editor (such as notepad), \n has no special meaning. It is simply two ASCII characters; '\' and 'n'.

In a C or C++ compiler, the \ character is an escape sequence, telling the compiler the following character(s) has special meaning.
http://www.cplusplus.com/forum/general/78208/

A newline character has a decimal value of 10.

How to go about it? Read a line of text in from the file. Iterate through the line of text looking for '\' followed by 'n'. When the pair is found, delete the '\' and replace the 'n' with '\n'. Note that because \ is an escape sequence, the proper character literal for a backslash is actually '\\'. When you reach the end of line, continue with reading the next line of text from the file until you reach eof.

Last edited on
Topic archived. No new replies allowed.