将文件内容字符对读入数组
在C++中,如何将文件的内容读入字符串数组?我需要一个由空格分隔的字符对组成的文件,如下所示:
cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc
c 可以是任何字符,包括空格!尝试:
ifstream myfile("myfile.txt");
int numPairs = 24;
string myarray[numPairs];
for( int i = 0; i < numPairs; i++) {
char read;
string store = "";
myfile >> read;
store += read;
myfile >> read;
store += read;
myfile >> read;
myarray[i] = store;
}
问题是这只是跳过空格,因此导致错误的值。我需要改变什么才能让它识别空格?
In C++, how can I read the contents of a file into an array of strings? I need this for a file that consists of pairs of chars separated by spaces as follows:
cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc
cc cc cc cc cc cc
c can be any char, including space! Attempt:
ifstream myfile("myfile.txt");
int numPairs = 24;
string myarray[numPairs];
for( int i = 0; i < numPairs; i++) {
char read;
string store = "";
myfile >> read;
store += read;
myfile >> read;
store += read;
myfile >> read;
myarray[i] = store;
}
The problem is that this just skips spaces alltogether, hence leading to wrong values. What do I need to change to make it recognize spaces?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是预期的行为,因为默认情况下
operator>>
会跳过空格。解决方案是使用
get
方法,这是一种低级操作,从流中读取原始字节而不进行任何格式化。顺便说一句,VLA(大小不固定的数组)在 C++ 中不是标准的。您应该指定一个常量大小,或者使用诸如
vector
之类的容器。That's expected behavior, since
operator>>
, by defaults, skips whitespace.The solution is to use the
get
method, which is a low level operation that reads raw bytes from the stream without any formatting.By the way, VLAs (arrays with a non constant size) are non standard in C++. You should either specify a constant size, or use a container such as
vector
.如果输入与您所说的完全相同,则以下代码将起作用:
If the input is exact like you say the following code will work: