[英]Reverse a string from a file in c++ using vectors
I'm trying to write a program that reads a text from a file (only strings) and reverse it. 我正在尝试编写一个程序,该程序从文件(仅字符串)中读取文本并将其反转。 The following code does that, but it doesn't take into account spaces between words: 下面的代码可以做到这一点,但是没有考虑单词之间的间隔:
#include<iostream>
#include<vector>
#include<fstream>
using namespace std;
int main(){
ifstream file("file.txt");
char i;
int x;
vector<char> vec;
if(file.fail()){
cerr<<"error"<<endl;
exit(1);
}
while(file>>i){
vec.push_back(i);
}
x=vec.size();
reverse(vec.begin(), vec.end());
for(int y=0; y<x; y++){
cout<<vec[y];
}
return 0;
}
If the text on the file is "dlroW olleH", the program would print out "HelloWorld". 如果文件上的文本是“ dlroW olleH”,则程序将打印出“ HelloWorld”。 What can I do so that it prints "Hello World" (with the space between both words)? 我该怎么做才能显示“ Hello World”(两个词之间有空格)?
The reverse
function is working perfectly fine, the problem lies here: reverse
功能运行正常,问题出在这里:
while(file>>i){
std::operator>>
skips spaces and new lines, you will need to use std::istream::getline
to avoid this or try std::noskipws
manipulator. std::operator>>
跳过空格和换行符,您将需要使用std::istream::getline
来避免这种情况,或者尝试使用std::noskipws
操纵器。
Usage: 用法:
#include <iostream> // std::cout, std::skipws, std::noskipws
#include <sstream> // std::istringstream
int main () {
char a, b, c;
std::istringstream iss (" 123");
iss >> std::skipws >> a >> b >> c;
std::cout << a << b << c << '\n';
iss.seekg(0);
iss >> std::noskipws >> a >> b >> c;
std::cout << a << b << c << '\n';
return 0;
}
Output: 输出:
123
1
As user4581301 pointed out, >>
will automatically skip any whitespace. 正如user4581301指出的, >>
将自动跳过任何空格。 You can disable this by using the std::noskipws
stream manipulator and changing file>>i
to file>>std::noskipws>>i
. 您可以通过使用std::noskipws
流操纵器并将file>>i
更改为file>>std::noskipws>>i
来禁用此功能。 A better solution altogether is to simply use std::getline
to read the whole string into an std::string
, reverse it, and print it out instead handling the characters individually. 更好的解决方案是简单地使用std::getline
将整个字符串读入std::string
,将其反转并打印出来,而不是单独处理字符。
#include <string>
#include <fstream>
#include <iostream>
#include <algorithm>
int main()
{
std::ifstream file("input.txt");
//insert error checking stuff here
std::string line;
std::getline(file, line);
//insert error checking stuff here
std::reverse(line.begin(), line.end());
std::cout << line << '\n';
}
Just a note about your code, you should declare variables only when they are used. 只是关于代码的注释,仅应在使用变量时声明它们。 For example, your variable x
is only used at the end of the program, but it is declared all the way at the top. 例如,变量x
仅在程序末尾使用,但始终在顶部声明。 using namespace std
can also be considered bad practice . using namespace std
也可以视为不良做法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.