Adversas Adversas - 7 days ago 6
C++ Question

How to add a space into an array

While the topic of the question isn't quite accurate, here's the problem. I have a file in which a person writes his text, for example 'Today is a very nice day' and i store it in a txt document. Then my task is to take all of these charaters and move them one letter further (a becomes b, z becomes a and so on). But I need to keep the spaces in their places.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>

using namespace std;

int main(){

string a;
string Code;
string New;

ifstream File ("Txt.txt");
File>>Code;

for (int i = 0; i<Code.size(); i++){
if (Code.at(i) >= 'A' && Code.at(i) <= 'V' || Code.at(i) >= 'a' && Code.at(i) <= 'v') {
a = Code.at(i) + 4;
New += a;
}
else if (Code.at(i) == 'W'){
a = 'A';
New += a;}
else if (Code.at(i) == 'X'){
a = 'B';
New += a;}
else if (Code.at(i) == 'Y'){
a = 'C';
New += a;}
else if (Code.at(i) == 'Z'){
a = 'D';
New += a;}
else if (Code.at(i) == 'w'){
a = 'a';
New += a;}
else if (Code.at(i) == 'x'){
a = 'b';
New += a;}
else if (Code.at(i) == 'y'){
a = 'c';
New += a;}
else if (Code.at(i) == 'z'){
a = 'd';
New += a;}
else if (Code.at(i) == ' '){
a = Code.at(i);
New += a;
}
}cout<<New;

return 0;
}


But the program only read the first word. How should I change the program to read all the text with all the spaces?

Answer

Use std::getline, like this:

std::string line;
std::ifstream file("file.txt");
std::getline(file, line); //loads one line

Btw using namespace std; is a bad practice, you should keep your global namespace clean and use std:: prefix. If you are really lazy, you can 'import' only important parts. using std::cin; etc.

Comments