Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从文本文件的每一行向字符串中输入N个字符?_C++_String_Function - Fatal编程技术网

C++ 如何从文本文件的每一行向字符串中输入N个字符?

C++ 如何从文本文件的每一行向字符串中输入N个字符?,c++,string,function,C++,String,Function,如果您在答案中编写代码,请将其编写为使用名称空间std;。否则我很难阅读:) #包括 #包括 #包括 使用名称空间std; int a;//a是文件中的行数 字符串字[100]; int main() { ifstream fd(“file.txt”); fd>>a; 对于(int i=0;i,我会考虑该文件可能有100多行(这将超过您的word-数组),并且我还会考虑该文件在a中所述的行数和实际行数方面可能不一致。鉴于此,请尝试以下操作: 字符串行; int i; for(i=0;getlin

如果您在答案中编写代码,请将其编写为使用名称空间std;。否则我很难阅读:)

#包括
#包括
#包括
使用名称空间std;
int a;//a是文件中的行数
字符串字[100];
int main()
{
ifstream fd(“file.txt”);
fd>>a;

对于(int i=0;i,我会考虑该文件可能有100多行(这将超过您的
word
-数组),并且我还会考虑该文件在
a
中所述的行数和实际行数方面可能不一致。鉴于此,请尝试以下操作:

字符串行;
int i;

for(i=0;getline(fd,line)&&I什么是
fd fd>>a;,它将显示文本文件中有多少行,这样我就知道我的for循环需要循环多少次。您是否将要读取的行数存储在文件中?很抱歉,响应太晚。在我尝试解决的练习中,通常在第一行中写入一个数字,告诉行数,数字或其他信息。然后我们在循环中使用该数字,这样我们就知道他们必须循环多少次。请回答!我并不在乎有100多行,因为练习非常具体,我正在准备我的编程考试(我尝试解决前几年的练习).但是你知道的越多越好!
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int a; // a is amount of lines in file
string word[100];

int main()
{
    ifstream fd("file.txt");
    fd >> a;
    for(int i=0; i<a; i++)
    {
        //here goes the code which inputs, let's say, 20 first characters of a line into string array - word[i].
    }
    fd.close();

    return 0;
}