如何将 space 添加到数组中
How to add a space into an array
虽然问题的主题不太准确,但这就是问题所在。我有一个文件,一个人在其中写下他的文本,例如 'Today is a very nice day',我将它存储在一个 txt 文档中。然后我的任务是获取所有这些字符并将它们进一步移动一个字母(a 变成 b,z 变成 a 等等)。但我需要保留空格。
#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;
}
但是程序只读了第一个字。我应该如何更改程序以读取包含所有空格的所有文本?
使用std::getline
,像这样:
std::string line;
std::ifstream file("file.txt");
std::getline(file, line); //loads one line
顺便说一下,using namespace std;
是一种不好的做法,您应该保持全局命名空间干净并使用 std::
前缀。如果实在懒,可以'import'只写重要的部分。 using std::cin;
等
指向文件末尾。
void openFile (ifstream& f)
{
const long LINE_LEN = 23;
int pos;
// position to 256 lines before end of file
f.open("demodoutcarr.txt");
f.seekg(0, ios::end);
pos = f.tellg();
pos -= LINE_LEN * NBR_RECORDS;
f.seekg(pos);
}
虽然问题的主题不太准确,但这就是问题所在。我有一个文件,一个人在其中写下他的文本,例如 'Today is a very nice day',我将它存储在一个 txt 文档中。然后我的任务是获取所有这些字符并将它们进一步移动一个字母(a 变成 b,z 变成 a 等等)。但我需要保留空格。
#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;
}
但是程序只读了第一个字。我应该如何更改程序以读取包含所有空格的所有文本?
使用std::getline
,像这样:
std::string line;
std::ifstream file("file.txt");
std::getline(file, line); //loads one line
顺便说一下,using namespace std;
是一种不好的做法,您应该保持全局命名空间干净并使用 std::
前缀。如果实在懒,可以'import'只写重要的部分。 using std::cin;
等
指向文件末尾。
void openFile (ifstream& f)
{
const long LINE_LEN = 23;
int pos;
// position to 256 lines before end of file
f.open("demodoutcarr.txt");
f.seekg(0, ios::end);
pos = f.tellg();
pos -= LINE_LEN * NBR_RECORDS;
f.seekg(pos);
}