存储在char数组中的文件中的c++行
c++ line from file stored in char array
我希望能够使用函数将整行读取到字符数组中。
示例输入文本为:
Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly
但是,我不知道如何将整行字符读入数组。我知道>>的分隔符是空白,但我不确定我是否将该分隔符改为"\n",如果它有效的话?
void buildList(char (*array)[25], ifstream& inputFile){
string line;
for (int i = 0; i < 5; i++)
getline(inputFile, line);
array[i] = line.c_str();
}
目前,这只会在我的输入中读取姓氏或名字,而不是整行。我不知道如何才能改变这一点。谢谢
首先,您肯定要在这里使用std::string
。一旦你这样做,您可以使用std::getline
:
std::vector<std::string>
buildList( istream& input )
{
std::vector<std::string> results;
std::string line
while ( std::getline( input, line ) ) {
results.push_back( line );
}
}
这将使代码更加简单和健壮。
如果你必须使用这样一个损坏的接口,那么有一个成员函数getline
:
for ( int i = 0; i != 5; ++ i ) {
input.getline( array[i], maxLength );
}
此外:函数应从不将std::ifstream&
作为参数(除非它要打开或关闭文件)。一应使用std::istream&
。
使用此-
void buildList(char (*array)[25], ifstream& inputFile){
for (int i = 0; i < 5; i++)
std::inputFile.getline(array[i],50);
}
getline
的第二个参数是要写入字符数组的最大字符数。
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到