文本文件c/c++的字符串用法
string usage with textfiles c/c++
我在使用字符串时遇到问题。所以我想写一个程序,把两个括号相乘,因为我有一些括号,每个括号有10个变量。我在一个.txt文件中放了一个括号,想读一读,然后打印到另一个txt文件中。我不确定具体的标志是否有问题。这是我阅读的文本
2*x_p*x_N-x_p^2+d_p-2*x_N*x_Q+x_Q^2-d_Q
这是它实际打印的
2*x_--x_p^++d_p-2*x_++x_Q^--
正如你所看到的,这是完全错误的。此外,我在执行后收到一个错误,但它仍然将其打印到.txt中
#include <stdio.h>
#include <string>
using namespace std;
int main()
{
int i;
const int size = 11;
string array[ size ];
FILE * file_read;
file_read = fopen( "alt.txt", "r" );
for( i = 0; i < size; i++ ) //Read
{
fscanf( file_read, "%s", &array[ i ] );
}
fclose( file_read );
FILE * file_write;
file_write = fopen( "neu.txt", "w" );
for( i = 0; i < size; i++ ) //Write
{
fprintf( file_write, "%s", &array[ i ] );
}
fclose( file_write ); printf("test");
return 1;
}
谢谢你的建议。您也可以使用iostream提出建议。
您正在混合C++和C形式的文件输入:
当你写:
fscanf( file_read, "%s", &array[ i ] );
C标准库希望您提供一个指向缓冲区的指针,在该缓冲区中,文件中读取的字符串将以C字符串的形式存储,即以null结尾的字符数组。
不幸的是,您提供了一个指向C++字符串的指针。因此,这将导致未定义的行为(很可能是内存损坏)。
解决方案1
如果你想继续使用C标准库文件i/o,你必须使用一个临时缓冲区:
char mystring[1024]; //for storing the C string
...
fscanf( file_read, "%1023s", mystring );
array[ i ] = string(mystring); // now make it a C++ string
请注意,格式略有更改,以避免在文件包含大于缓冲区的字符串时出现缓冲区溢出的风险。
解决方案2
如果您学习C++(查看C++标记和字符串头),我强烈建议您查看C++库中的fstream
。它的设计可以很好地与字符串配合使用。
下面是它的样子:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
const int size = 11;
string array[ size ];
ifstream file_read( "alt.txt");
for(int i = 0; i < size && file_read >> array[ i ]; i++ ) //Read
;
file_read.close();
ofstream file_write("neu.txt");
for(int i = 0; i < size; i++ ) //Write
file_write << array[ i ] <<" "; // with space separator
file_write.close();
cout << "test"<<endl;
return 0;
}
当然,接下来你应该考虑的是用向量取代经典数组(你不必事先定义它们的大小)。