Code won't write to file.

It creates the .txt file but it doesn't write to it.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  void findLists () {
	 if (CreateDirectoryA ("ToDoLists", NULL)) {
	 //Directory created
	 }
	 else if (ERROR_ALREADY_EXISTS == GetLastError ()) {
	 //Directory already exists
	 }
	 else {
	 //Failed for some other reason
	 }
}


void createList () {
	string listItem;
	int continueList;

	string fileName;
	cout << "Enter a file Name, Example - example.txt" << endl;
	cin >> fileName;
	cin.ignore();
	ofstream myfile (fileName);

	cout << "Enter a list item >  ";
	myfile.open(fileName);
	getline(cin, listItem);
	myfile << listItem;
}


void createItems () {
	
}


void writeList () {

}


void readList () {

}


void deleteList () {

}


int main () {
	findLists();
	createList ();

	system ("PAUSE");
	return 0;
}
The file is already opened by line 22: ofstream myfile (fileName);
Comment out (or delete) line 25: myfile.open(fileName);
That worked. Now im trying to add in a loop, but after I enter the first item it display a continuous amount of characters.

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
28

void createList () {
	string listItem;
	bool userDone = false;
	string fileName;

	cout << "Enter a file Name, Example - example.txt" << endl;
	cin >> fileName;
	cin.ignore();
	ofstream myfile (fileName);
 
	while (userDone = "no")	{
		    
			cout << "Enter a list item >  ";

			getline(cin, listItem);
			myfile << listItem;
			

			cout << "Are you done? yes or no? >  ";
			cin   >> userDone;
			
	}
	
	myfile.close ();

}
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
28
29
30
31
32
33
34
void createList () {

    std::cout << "Enter a file Name, Example - example.txt\n" ;
    std::string fileName ;
    std::cin >> fileName; // leaves the new line in the input buffer
    std::cin.ignore( 1000, '\n' ) ; // extract and discard the new line

    std::ofstream myfile(fileName);

    if( myfile.is_open() ) {

        bool userDone = false ;
        std::string listItem ;

        while( !userDone &&
               std::cout << "Enter a list item >  " &&
               std::getline( std::cin, listItem) ) {

            myfile << listItem << '\n' ;

            char yn ;
            std::cout << "Are you done (y or n)? ";
            std::cin  >> yn; // leaves the new line in the input buffer
            std::cin.ignore( 1000, '\n' ) ; // extract and discard the new line

            userDone = ( yn == 'y' ) || ( yn == 'Y' ) ; // true if y was entered
        }
    }

    else { // myfile.is_open() == false

        std::cerr << "could not open file '" << fileName << "' for writing\n" ;
    }
}
Topic archived. No new replies allowed.