使用向量将字符串从C 中的文件转换
Reverse a string from a file in c++ using vectors
我正在尝试编写一个程序,该程序从文件(仅字符串(中读取文本并将其反转。以下代码这样做,但它没有考虑到单词之间的空间:
#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;
}
如果文件上的文本为" dlrow olleh",则该程序将打印出" Helloworld"。我该怎么办,它打印出" Hello World"(两个单词之间的空间(?
指出用户4581301,>>
将自动跳过任何空格。您可以使用std::noskipws
流操纵器并将file>>i
更改为file>>std::noskipws>>i
来禁用此功能。一个更好的解决方案是简单地使用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';
}
只是关于您的代码的注释,您只能在使用变量时声明它们。例如,您的变量x
仅在程序的末尾使用,但在顶部一直声明。using namespace std
也可以被视为不良练习。
reverse
函数工作正常,问题在于:
while(file>>i){
std::operator>>
跳过空间和新行,您需要使用std::istream::getline
避免这种情况或尝试std::noskipws
操纵器。
用法:
#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;
}
输出:
123
1
相关文章:
- 将生成文件转换为 CMakeLists.txt等效项
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 如何使用 CreateProcess 调用 tshark 将捕获文件转换为 txt
- 使用emscripten将c++文件转换为wasm时出错
- 将Qt qml文件转换为位图图像
- (对于C++)读取类型从文件转换为 2D 数组
- 使用向量将字符串从C 中的文件转换
- 编写一个 C++ 程序以将文本文件转换为 HTML 文件
- 如何在 C++ 中将矩阵市场文件转换为矩阵
- 是否可以将信息从XML文件转换为CPP
- 将 ASCII 文件转换为 C++ 的二进制格式
- 将生成文件转换为CMakeLists;无法加载共享库
- FlatBuffers:未支撑的工会向量错误将JSON文件转换为二进制文件
- 如何使用 qt 将 Linux 文本文件转换为 Windows 文本文件
- 如何将可执行文件转换为 C++ 文件以达到代码峰值
- 将windows软件中的未知数据库文件转换为MySqli数据库
- 如何将 .npy 文件转换为 .binaryproto
- 使用ICEBuilder将ICE文件转换为C++
- 将文件转换为字符串数组C++
- 在编译时将文本文件转换为字符串