【发布时间】:2015-01-16 22:15:08
【问题描述】:
我正在尝试制作一个程序,该程序将打开一个包含此格式名称列表的 txt 文件(忽略项目符号):
- 3 马克
- 4 拉尔夫
- 1 编
- 2 凯文
并将根据前面的数字创建一个带有组织名称的文件:
- 1 编
- 2 凯文
- 3 马克
- 4 拉尔夫
我认为我在第 40 行遇到了问题,我尝试将存储在字符串中的数字与存储在 int 中的数字进行比较。
我想不出任何其他方法来解决这个问题,任何建议都会很棒!
#include <iostream>
#include <fstream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
ifstream in;
ofstream out;
string line;
string collection[5];
vector <string> lines;
vector <string> newLines;
in.open("infile.txt");
if (in.fail())
{
cout << "Input file opening failed. \n";
exit(1);
}
out.open("outfile.txt");
if (out.fail())
{
cout << "Output file opening failed. \n";
exit(1);
}
while (!in.eof())
{
getline(in, line);
lines.push_back(line);
}
for (int i = 0; i < lines.size(); i++)
{
collection[i] = lines[i];
}
for (int j = 0; j < lines.size(); j++)
{
for (int x = 0; x < lines.size(); x--)
{
if (collection[x][0] == j)
newLines.push_back(collection[x]);
}
}
for (int k = 0; k < newLines.size(); k++)
{
out << newLines[k] << endl;
}
in.close( );
out.close( );
return 0;
}
【问题讨论】:
-
你试过投射它们吗?这究竟是哪种语言?
-
对不起,我应该在帖子中包含它。它是 C++。我只是尝试将变量 j 转换为 char 并且还没有任何运气。
-
您需要有序集合或称为集合类对象,以便您可以存储排序的名称记录(为此使用 std::sort 对象)。如果您仍然卡住,请尝试使用这些并更新您的代码。只是尽量不要为你写代码,因为你已经表现出自己写东西的努力。
-
我还没有使用过套装,所以我不太确定我是否跟随。可以举个例子吗?
标签: c++ string numbers int compare