[英]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.