I am having an issue with my last for loop in my program. It is not storing any value for position 0 and it's printing out the null values. Here is my program.
#include <iostream>
#include <string>
#include <fstream>
#include <ctype.h>
usingnamespace std;
int main() {
ofstream myfile("string.dat");
string str1;
cout << "Please enter a sentence : ";
getline(cin, str1);
if (myfile.is_open())
{
myfile << str1;
myfile.close();
}
else cout << "Unable to open file";
cout << endl;
cout << endl;
cout << endl;
intconst size = 1000;
char alpha[size]; // declaring the array
int i=0;
ifstream file("string.dat");
if (file.is_open())
{
while (file.getline(alpha, size)) // telling the program where to get the string from the file
{
while (alpha[i] != '\0') { // populating and printing out the array up until the null values
alpha[i] = toupper(alpha[i]);
cout << alpha[i];
i++;
}
}
file.close();
}
else cout << "Unable to open file";
cout << endl;
cout << endl;
for (int i = 0; i < size; i++) {
if (alpha[i] != '\0') {
cout << alpha[i];
}
}
return 0;
}
There is a lack of symmetry in the file handling. At line 18 a single string is written to the file which is then closed.
At line 32, rather than reading a single line from the file, there is a while loop. The first iteration proceeds ok. Then the second time, the getline fails to read anything, it writes a null byte to alpha[0]. Then at line 47 the entire array alpha is processed, any non-zero character is output.