[英]Reading from a text file into an array
I'm just a beginner for C++我只是 C++ 的初学者
I want to read the text file (maximum of 1024 words) into an array, and I need to ignore all single character words.我想将文本文件(最多 1024 个字)读入一个数组,我需要忽略所有单字符字。 Can you guys help me to discard words that are single characters to avoid symbols, special characters.
你们能帮我丢弃单个字符的单词以避免符号、特殊字符吗?
This is my code:这是我的代码:
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
const int SIZE = 1024;
void showArray(string names[], int SIZE){
cout << "Unsorted words: " << endl;
for (int i = 0; i < SIZE; i++){
cout << names[i] << " ";
cout << endl;
}
cout << endl;
}
int main()
{
int count = 0;
string names[SIZE];
// Ask the user to input the file name
cout << "Please enter the file name: ";
string fileName;
getline(cin, fileName);
ifstream inputFile;
inputFile.open(fileName);
// If the file name cannot open
if (!inputFile){
cout << "ERROR opening file!" << endl;
exit(1);
}
// sort the text file into array
while (count < SIZE)
{
inputFile >> names[count];
if (names[count].length() == 1);
else
{
count++;
}
}
showArray(names, SIZE); // This function will show the array on screen
system("PAUSE");
return 0;
}
If you change names
into a std::vector
, then you can populate it using push_back
.如果将
names
更改为std::vector
,则可以使用push_back
填充它。 You could fill names
like this.你可以像这样填写
names
。
for (count = 0; count < SIZE; count++)
{
std::string next;
inputFile >> next;
if (next.length() > 1);
{
names.push_back(next);
}
}
Alternatively you could fill all the words into names
and then utilize the Erase–remove idiom .或者,您可以将所有单词填入
names
,然后使用Erase-remove idiom 。
std::copy(std::istream_iterator<std::string>(inputFile),
std::istream_iterator<std::string>(),
std::back_inserter<std::vector<std::string>>(names));
names.erase(std::remove(names.begin(), names.end(),
[](const std::string& x){return x.length() == 1;}), names.end());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.