简体   繁体   English

从文本文件中提取字符串列表

[英]Extracting a list of strings from a text file

I am trying to extract a vector that contains all strings in a txt file using c++, which I have almost no experience. 我正在尝试使用c ++提取一个包含txt文件中所有字符串的向量,而我几乎没有经验。 In java or matlab, this would have been really easy, all I have to do is 在Java或Matlab中,这真的很容易,我要做的就是

  1. Read a long list of character sequence from the txt file. 从txt文件中读取一长串字符序列。

  2. Loop through this sequence and extract the strings. 遍历此序列并提取字符串。

In c++ there seems to be a lot more things that I have to deal with, for example, I am asked to 在c ++中,似乎还有很多事情我需要处理,例如,我被要求

  1. Add a new C++ header (.h) file to my program and in it please declare an enumeration for the different array indices that are relevant. 在我的程序中添加一个新的C ++头文件(.h),并在其中声明一个相关的不同数组索引的枚举。

  2. Declare a file parsing function that takes two parameters: a reference to a Standard Template library (STL) vector of C++ style strings (eg, of type vector &), and a C-style string (of type char *); 声明一个带有两个参数的文件解析函数:对C ++样式字符串(例如,向量&的类型)的标准模板库(STL)向量的引用,以及对C样式的字符串(字符*的类型)的引用;

Non of these makes too much sense to me. 这些都不对我有太大意义。 Is there a good source to get help on this? 是否有很好的资源来获得帮助?

To read the file: 读取文件:

std::ifstream in("foo.txt");
std::stringstream buffer;
buffer << in.rdbuf();

After that there are various ways to split up the contents, depending on your exact requirements. 之后,根据您的确切要求,可以使用多种方法拆分内容。

Since you are new to C++, I recommend you check out this website: http://www.cplusplus.com/ 由于您不熟悉C ++,因此建议您访问以下网站: http : //www.cplusplus.com/

Parsing from input files is relatively easy if you are using command line to run your program. 如果使用命令行运行程序,则从输入文件进行解析相对容易。 Simply include the main function as follows: 只需包括以下主要功能:

int main(int argc, char **argv)

Then, access the parameters passed in using argv as an array: 然后,访问使用argv作为数组传递的参数:

var = argv[0];

Declare a char array and then use that array to capture each line of the file. 声明一个char数组,然后使用该数组捕获文件的每一行。

char input[MAX_SIZE];
while(cin.getline(input, MAX_SIZE))
{
    //Each time this executes, input contains all characters of a line, like a string
    //e.g. make it a String and add it to a vector of type String
    //do something with input[]
}

Your file parsing function can receive the two parameters that I specified in the main parameters, but these must also be declared as parameters to main. 您的文件解析函数可以接收我在main参数中指定的两个参数,但是还必须将它们声明为main的参数。 Then, your function can grab the input the way I demonstrated. 然后,您的函数可以按照我演示的方式获取输入。

As for your header file, I'm not exactly sure what kinds of enumerations you mean, but you can find syntax and rules for enumeration on the site given above. 至于头文件,我不确定您要指的是哪种枚举,但是您可以在上面给出的站点上找到枚举的语法和规则。 If I recall correctly, enumerations are similar in Java and C++. 如果我没记错的话,Java和C ++中的枚举类似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM