简体   繁体   English

如何从文本文件中读取特定数量的字符

[英]How to read a specific amount of characters from a text file

I tried to do it like this 我试着这样做

 #include <iostream>
 #include <fstream>

using namespace std;

int main()
{
    char b[2];
    ifstream f("prad.txt");
    f>>b ;
    cout <<b;
    return 0;
}

It should read 2 characters but it reads whole line. 它应该读取2个字符,但它读取整行。 This worked on another language but doesn't work in C++ for some reason. 这适用于另一种语言但由于某种原因无法在C ++中运行。

You can use read() to specify the number of characters to read: 您可以使用read()指定要读取的字符数:

char b[3] = "";
ifstream f("prad.txt");

f.read(b, sizeof(b) - 1); // Read one less that sizeof(b) to ensure null
cout << b;                // terminated for use with cout.

This worked on another language but doesn't work in C++ for some reason. 这适用于另一种语言但由于某种原因无法在C ++中运行。

Some things change from language to language. 有些事情因语言而异。 In particular, in this case you've run afoul of the fact that in C++ pointers and arrays are scarcely different. 特别是,在这种情况下,你已经碰到了这样一个事实:在C ++中,指针和数组几乎没有什么不同。 That array gets passed to operator>> as a pointer to char, which is interpreted as a string pointer, so it does what it does to char buffers (to wit read until the width limit or end of line, whichever comes first). 该数组作为指向char的指针传递给operator >>,它被解释为字符串指针,因此它对char缓冲区执行的操作(直到宽度限制或行尾,以先到者为准)。 Your program ought to be crashing when that happens, since you're overflowing your buffer. 当发生这种情况时,你的程序应该崩溃,因为你的缓冲区溢出了。

istream& get (char* s, streamsize n );

Extracts characters from the stream and stores them as a c-string into the array beginning at s. 从流中提取字符并将它们作为c字符串存储到从s开始的数组中。 Characters are extracted until either (n - 1) characters have been extracted or the delimiting character '\\n' is found. 提取字符,直到提取(n-1)个字符或找到分隔字符'\\ n'。 The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation. 如果在输入序列中到达文件末尾或者在输入操作期间发生错误,则提取也会停止。 If the delimiting character is found, it is not extracted from the input sequence and remains as the next character to be extracted. 如果找到分隔字符,则不从输入序列中提取分隔字符,并将其保留为要提取的下一个字符。 Use getline if you want this character to be extracted (and discarded). 如果要提取(并丢弃)此字符,请使用getline。 The ending null character that signals the end of a c-string is automatically appended at the end of the content stored in s. 用信号通知c-string结尾的结束空字符会自动附加在s中存储的内容的末尾。

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

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