[英]Finding the longest line in a file, Comparison between signed and unsigned integer expressions
大家好,我正在处理一个查找文件中最长单词和行的分配,我目前正在处理它,但在收到此错误时卡住了。
错误:有符号和无符号整数表达式之间的比较 [-Werror=sign-compare]
现在我明白了这个错误,但我很难修复它,我已经尝试在我自己的第一个课程中修复它,但被迫求助于此寻求帮助。
#include <iostream>
#include<fstream>
using namespace std;
int main(int argc, char *argv[]) {
int longest = 0;
string line;
if(argc == 0)
{
cout << " " << endl;
}
else
{
for(int i = 1;i<argc;i++){
ifstream file (argv[i]); //declare in the for loop
if (!file.is_open() ){
cout << argv[i] << " FILE NOT FOUND\n"; // watch out for /n
}
else{
while (getline(file,line))
{
if(line.size() > longest){
longest = line.size();
cout << "The length of the longest Line is: " << longest << endl;
}
}
}
}
}
}
我知道错误在这里:
if(line.size() > longest){
编辑:解决方案:这里的修复是使用 size_t 而不是 int 来声明最长,我在尝试修复它时尝试做的是在 if 语句中包含 size_t,这对我来说是完全错误的。
错误:整数最长 = 0; 右:size_t 最长 = 0; 但这仅适用于此类情况。
如前所述,您应该使longest
未签名。
此外,检查argc==0
应该是argc<2
(因为argv[0]
是程序名称)。
最后,只要一行比当前的最大值更长,就重新打印“最长的行”声明似乎很奇怪。
奖励:没有真正需要将数据读入字符串,这会产生内存分配成本。 您可以只计算换行符之间的字节数。
这是我的简化版:
#include <vector>
#include <iostream>
#include <fstream>
#include <iterator>
namespace {
struct accumulator {
size_t peak = 0;
void operator()(size_t n) { peak = std::max(n, peak); }
};
}
int main(int argc, char **argv) {
accumulator sample;
for(auto fname : std::vector<std::string>(argv+1, argv+argc)) {
std::ifstream ifs(fname, std::ios::binary);
if (!ifs) {
std::cout << fname << " FILE NOT FOUND\n";
continue;
}
std::istreambuf_iterator<char> f(ifs), l;
auto scan_until = [&](char delimiter) {
size_t count = 0;
while (f!=l && *f++ != delimiter) ++count;
return count;
};
while (f!=l)
sample(scan_until('\n'));
}
std::cout << "The length of the longest line is: " << sample.peak << "\n";
}
在自己的源上运行时:
The length of the longest line is: 78
奖金
对每个文件打印最长行的简单更改:
/Archive2/8b/001ad4e031178d/main.cpp 44
/Archive2/8b/00964b446531eb/main.cpp 37
/Archive2/8b/01880ea6d95d38/main.cpp 50
/Archive2/8b/029f129c393ce5/main.cpp 63
... 390 lines snipped...
/Archive2/8b/f94c53ac4aee45/main.cpp 93
/Archive2/8b/f9ab4b38599e1a/main.cpp 80
/Archive2/8b/fabac3a5309ea7/main.cpp 72
/Archive2/8b/fb63a91a5b2b29/main.cpp 33
/Archive2/8b/fba5d4cf806d91/main.cpp 95
/Archive2/8b/fc2fbcfddff198/main.cpp 42
/Archive2/8b/fc4bbeb11aa3e9/main.cpp 78
/Archive2/8b/fc56c06f6ed2a1/main.cpp 37
/Archive2/8b/fd5770ca49eb30/main.cpp 78
/Archive2/8b/fe0b1121edfb0a/main.cpp 59
/Archive2/8b/ff0f709404e6a1/main.cpp 84
Overall longest line: 1353
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.