【问题标题】:Why does unsigned variable contain wrong value [closed]为什么无符号变量包含错误的值[关闭]
【发布时间】:2014-10-24 15:27:47
【问题描述】:

我正在尝试从包含 HTML 的文本文件中获取 ID。 ID 是从 HTML 中的 URL 中提取的,因此我循环文件以找到正确的行,然后使用子字符串获取正确的信息。有两种不同类型的 ID,所以我有两种不同的功能。

第二个(getYearId)工作正常,但第一个导致代码在当前被注释掉的部分中止。如您所见,我尝试输出first1 的值,却发现它的输出是alue=",这是我假设first 应该相等的一部分。我做错了什么?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <regex>
using namespace std;

void getSyllabiId() {
string line;
ifstream myfile("syllabi.txt");
if (myfile.is_open()) {
    while (getline(myfile, line)) {
        if (line.find("View Assignments") != string::npos) {
            string startDel = "syllabusid";
            string endDel = "View";
            unsigned int first1 = line.find(startDel);
            unsigned int last1 = line.find(endDel);

            cout << first1 + "\n";

            //string syllabusID = line.substr(first1, last1 - first1);
            //syllabusID = syllabusID.substr(startDel.size());
            // cout << syllabusID + "\n";

        }
    }
    myfile.close();
}
else cout << "Unable to open file.";
}

void getYearId() {
string line;
ifstream myfile("syllabi.txt");
if (myfile.is_open()) {
    while (getline(myfile, line)) {
        if (line.find("2014-2015</option>") != string::npos) {
            string startDel = "value=\"";
            string endDel = "\" selected";
            unsigned int first = line.find(startDel);
            unsigned int last = line.find(endDel);
            string yearID = line.substr(first, last - first);
            yearID = yearID.substr(startDel.size());
            cout << yearID + "\n";
        }
    }
    myfile.close();
}
else cout << "Unable to open file";
}

int main () {

getYearId();
getSyllabiId();

string x;
cin >> x;

return 0;
}

【问题讨论】:

  • unsigned int first1 被声明和定义了两次..
  • first1 + "\n" 是一个问题:您不能使用 + 运算符将 int 与 C++ 中的字符串连接起来。试试这个:cout &lt;&lt; first1 &lt;&lt; endl;
  • 这个没有弹出编译器错误是怎么来的
  • double first1 实际上是我刚刚犯的一个错误,忘记删除,没有double first1 问题仍然存在。但我会试试你的解决方案@RPGillespie。
  • 您没有检查find 的结果来确定是否找到了搜索条件。

标签: c++ unsigned


【解决方案1】:

问题是我从未检查过first1last1 是否有值,因此很明显在一个(或多个实例)中,其中一个不会导致代码中止。

【讨论】:

  • 如果是解决方案,尽快标记为接受。
  • 它说我要等两天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 1970-01-01
  • 1970-01-01
  • 2016-06-14
  • 1970-01-01
  • 2010-10-11
  • 2016-03-24
相关资源
最近更新 更多