从文本文件读取到数组
Reading from a text file into an array
我只是C
的初学者我想将文本文件(最多为1024个单词)读为一个数组,我需要忽略所有单个字符单词。你们能帮我丢弃单个字符以避免符号,特殊字符的单词吗?
这是我的代码:
#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;
}
如果将names
更改为std::vector
,则可以使用push_back
填充它。您可以这样填充names
。
for (count = 0; count < SIZE; count++)
{
std::string next;
inputFile >> next;
if (next.length() > 1);
{
names.push_back(next);
}
}
另外,您可以将所有单词填充到names
中,然后使用擦除 - 删除成语。
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());
相关文章:
- 从锯齿状数组读取
- 是否很好地定义了强制转换为仅由 char[] 组成的结构并从该数组读取?
- 如何按字符从文件到2D数组读取字符
- 双维数组读取错误
- 动态分配的数组C 读取句子并打印单词
- ESP8266异常在尝试从字节数组读取float时
- C++无法从 2D 字符串数组读取
- Win32 C/C++从字节数组读取BMP宽度和高度
- 在执行期间将大型多维数组读取和写入二进制文件并返回数组
- 从 BYTE 数组读取 32 位整数.VC++
- 从十六进制数组读取 Int
- 从十六进制数组读取双精度到向量
- 通过数组C++读取学生的成绩
- 使用迭代器数组读取稀疏信息
- 从文件到字符串再到数组读取数字
- 直接从数组读取时超出了绑定地址
- 转换为空指针后从char数组读取int值
- 动态数组读取
- 从字节数组读取类型的模板方法的问题
- 从文件中以单独的数组读取整数,每次一个数字,在c++中