【发布时间】:2013-07-13 05:50:49
【问题描述】:
我不知道如何在几段左右的时间内阅读,而不是把每个单词放在结构中,而不是计算有多少个独特的单词。
我知道如何读取数据,只是不从有一行的字符串中传输一个单词。正如我之前在几段中所说的那样
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
struct words
{
char unique[21];
int count;
} test;
void inputFile (words essay[100]);
int search (int index, int subscript, int integer,words essay[100]);
int main()
{
words essay[100];
inputFile (&test);
cout << essay[0].unique<<test.count;
return 0;
}
void inputFile (words essay[100])
{
char fileName[81];
char copyName[81];
cout << "What is the name of the input file? \n";
cin >> fileName;
ifstream infile;
ofstream outfile;
int count = 0;
char line [81];
int ch;
infile.open(fileName);
outfile.open(copyName);
while ((ch = infile.peek()) != EOF)
{ // while not end of file
infile.getline (line[81].unique, 81);
cout << "Copying: " << line << endl;
count++;
outfile << essay << endl;
}
cout << "There were " << count << " lines copied\n";
cout << endl;
// close both files
infile.close ();
outfile.close ();
};
/*int search (int index, int subscript, int integer, struct words essay[100])
{
string key;
key = test.unique;
int n;
n = test.count;
int i;
i = 0;
while (i < n && essay[i] != key)
i++;
if (i == n)
{
i = -1;
}
return i;
};*/
【问题讨论】:
-
该代码是否编译?乍一看它不应该......仅供参考,计算文本中的单词是一项简单的任务,很多答案都描述了如何做到这一点。 stackoverflow.com/questions/16867944/…
-
你不必偷看。只需写
while (infile.getline(…)) { … }。顺便说一句line[81].unique没有意义;你想在那里做什么?无论如何,您应该将line定义为std::string并使用std::getline(infile, line)而不是infile.getline(…)。 -
如果您明确谈论 C++ 字符串,为什么包括 cstring?使用
std::string(Header) -
它应该编译是的,并且检查该链接。 line[81].unique 是我的错,我之前尝试过一些东西但显然没有修复它,我试图将文件读入结构,只是尝试不同的东西,因为我无法让它工作。我们刚刚在示例中包含 cstring 的书,所以我想我必须包含它。再次感谢
-
@alexbuisson 链接没有帮助,因为他们使用地图,我不能使用它,我明白他们在做什么我只是不明白如何获取我读入的字符串(我可以阅读在数据中就好了),而不是在结构中分成单词