gpt4 book ai didi

c++ - CodeEval 挑战 : Reverse strings in input file

转载 作者:行者123 更新时间:2023-11-30 03:47:29 24 4
gpt4 key购买 nike

我决定在明年参加正式类(class)之前开始学习 C++,我已经从 CodeEval 和 Project Euler 上的一些简单挑战开始。在这一个中,您必须获取一个包含单词字符串的输入文件,并且您必须输出文件中单词反转的行。这样一个具有以下输入的文件

1:这是第一行

2:这是第二行

最终会变成

1:一行是This

2:两行是This

我编写了以下程序来做到这一点,除了没有正确地反转字符串,而是完全反转单词之外,尽管编译时没有错误或警告,但它还是出现了段错误。我假设我错过了一些关于 C++ 中适当内存管理的内容,但我不确定它是什么。那么有人可以启发我在内存管理方面我错过了什么吗?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
int main(int argc, char** argv)
{
std::string filename = argv[1]; //has to be argv[1], argv[0] is program name
std::string output_string; //final output
std::string line; //Current line of file
std::ifstream read(filename.c_str());
if(read.is_open()){
while(std::getline(read,line)){
std::string temp;
std::istringstream iss;
iss.str(line);
while(iss >> temp){ //iterates over every word
output_string.insert(0,temp); //insert at the start to reverse
output_string.insert(0," "); //insert spaces between new words
}
output_string.erase(0,1); //Removes the space at the beginning
output_string.insert(0,"\n"); //Next line
}
output_string.erase(0,1); //Remove final unnecessary \n character
read.close();
}
else{
std::cout<<"Unable to open file\n";
}
for(unsigned int i = output_string.length(); i>=0;i--){
std::cout<<output_string[i];
}
std::cout<<"\n";
}

最佳答案

for(unsigned int i = output_string.length(); i>=0;i--){
std::cout<<output_string[i];
}

段错误发生在这里;您可能会从带有一些附加标志的编译器中获得警告。例如g++ 对 -Wall 不产生警告,但对 -Wextra 产生两个警告:一个关于 argc 没有被使用,另一个关于这个循环永不终止。

这里的问题是双重的:正如长颈鹿船长所说,您的起点超出了弦线的实际长度;而且条件 i >= 0 将始终为真,因为 i 是无符号的。因此,一旦它达到 0,下一次递减将导致它环绕到可能的最高值,然后您肯定获得越界内存访问。

报告的警告是:

reverse.cpp:31:49: warning: comparison of unsigned expression >= 0 is always true [-Wtype-limits]
for(unsigned int i = output_string.length(); i>=0;i--){

此外,正如长颈鹿船长所说,您正在反转整个文件,而不仅仅是每一行。因此,您可以只反转每一行并在完成该行后将其输出,而不是存储整个输出以备后用。

下面是整个程序,为了避免任何警告并获得正确的输出,只作了极少的改动。主要变化是将 output_string 的所有使用移至读取循环中。

int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "Need a file to process!" << std::endl;
return 1;
}
std::string filename = argv[1]; //has to be argv[1], argv[0] is program name
std::string line; //Current line of file
std::ifstream read(filename.c_str());
if(read.is_open()){
while(std::getline(read,line)){
std::string output_string; //final output
std::string temp;
std::istringstream iss;
iss.str(line);
while(iss >> temp){ //iterates over every word
output_string.insert(0,temp); //insert at the start to reverse
output_string.insert(0," "); //insert spaces between new words
}
output_string.erase(0,1); //Removes the space at the beginning
std::cout << output_string << std::endl;
}
read.close();
}
else{
std::cout<<"Unable to open file\n";
}
}

关于c++ - CodeEval 挑战 : Reverse strings in input file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33666217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com