用c++将文件中的一行文本复制到字符串中
Copy one line of text from a file to a string in c++
我需要从c++中的文本文件中复制一行文本,我有一个程序可以找到单词所在的行,所以我决定如果我可以只取每一行并将其加载到字符串中,我可以逐行、逐字符串搜索,以找到正确的单词及其在文件中的位置(以字符而非行为单位)。我们将不胜感激。
编辑:我找到了我用来定位行的代码
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
ifstream in_stream; //declaring the file input
string filein, search, str, replace; //declaring strings
int lines = 0, characters = 0, words = 0; //declaring integers
char ch;
cout << "Enter the name of the filen"; //Tells user to input a file name
cin >> filein; //User inputs incoming file name
in_stream.open (filein.c_str(), ios::in | ios::binary); //Opens the file
//FIND WORDS
cout << "Enter word to search: " <<endl;
cin >> search; //User inputs word they want to search
while (!in_stream.eof())
{
getline(in_stream, str);
lines++;
if ((str.find(search, 0)) != string::npos)
{
cout << "found at line " << lines << endl;
}
}
in_stream.seekg (0, ios::beg); // the seek goes here to reset the pointer....
in_stream.seekg (0, ios::beg); // the seek goes here to reset the pointer.....
//COUNT CHARACTERS
while (!in_stream.eof())
{
in_stream.get(ch);
cout << ch;
characters ++;
}
//COUNT WORDS
in_stream.close ();
system("PAUSE");
return EXIT_SUCCESS;
}
您只需要一个循环就可以实现这一点。你的循环应该是这样的:
while (getline(in_stream, str))
{
lines++;
size_t pos = str.find(search, 0);
if (pos != string::npos)
{
size_t position = characters + pos;
cout << "found at line " << lines << " and character " << position << endl;
}
characters += str.length();
}
我还建议您不要混合int和size_t类型。例如,字符应声明为size_t,而不是int。
相关文章:
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何使代码打印文本文件中的第一行?
- 如何在C++中以这种方式返回一行文本?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 需要从存档中读取一行文本.txt直到找到"hhh",然后转到下一行
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 到达分隔符时跳到文本文件的下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文本文件中随机选取一行
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 为什么这一行不输出我的文本文件?
- 代码无尽写入文本文件的第一行
- 如何从文本文件中读取一行并将其分为不同的变量
- C 在同一行中左右显示文本
- 以 LPCTSTR 开头编写另一行文本的最佳方法是什么?
- 阅读同一行上用双引号括起来的文本,并拒绝在不同行上关闭的双引号
- C :使用getline从文本文件中输入,要么跳过第一行,要么将其余部分弄乱
- C++ ->尝试逐字阅读一行文本。如何使指针等效于用于存储输入的当前二维数组
- 如何解决此问题,我需要从文本文件中导出一行