[英]How to read strings by line in C++ from .txt file
我目前有两个.txt文件,一个文件包含字符,我希望创建一个文件流并从该文件中获取字符并将它们放入字符数组中。
然后,我还有一个文本文件,在不同的行上有6个字符串,我需要将它们添加到字符串数组中,到目前为止,这是我的代码。当我尝试将“ words”的值放入时,我有一个小错误我的字符串文件将字符串数组放入数组中的每个位置。
//Gets the characters from the textfile and creates an array of characters.
char ch;
fstream fin("text1.txt", fstream::in);
while (fin >> noskipws >> ch) {
char letters[5];
cout << ch;
for (int i = 0; i < 14; ++i)
{
ch >> letters[i];
}
}
fin.close();
//Get the words from the file and add into an array of strings
string words;
fstream fin2("search1.txt", fstream::in);
while (getline(fin2, words)) {
string wordsArray[6];
cout << words;
for (int i = 0; i < 6; ++i)
{
words >> wordsArray[i];
}
}
fin2.close();
根据您的标题,您可以使用以下命令逐行阅读文本:
std::string text_line;
while (std::getline(input_stream, text_line))
{
// ...
}
要读取字符串中的单词 ,可以使用std::istringstream
:
std::string word;
std::istringstream text_stream(text_line);
while (text_stream >> word)
{
// Process the word
}
好的,所以这里有代码,从文本文件中提取一行字符,并将它们放入char []数组中
char ch;
char chArray[14];
fstream fin1("text1.txt", fstream::in);
if (fin1.is_open())
{
cout << "File of characters Opened successfully!!!. Reading data from file into array" << endl;
while (!fin1.eof()) {
for (int i = 0; i < 14; ++i) {
fin1.get(ch);
chArray[i] = ch;
cout << chArray[i] << endl;
}
}
}
现在,我需要以某种方式将字符数组转换为单个字符串,以便我可以将它们与包括单词的字符串数组进行比较。
有没有一种方法可以简单地将该数组转换为字符串数组?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.