我在使用字符串时遇到了问题。所以我有了编写一个程序的想法,它将两个括号相乘,因为我有一些有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提出建议。
答案 0 :(得分:2)
您正在混合使用C ++和C形式的文件输入:
当你写:
fscanf( file_read, "%s", &array[ i ] );
C标准库期望您提供一个指向缓冲区的指针,在该缓冲区中,文件中读取的字符串将以C字符串的形式存储,该字符串是一个以空字符结尾的字符数组。
不幸的是,您提供了指向C ++字符串的指针。因此,这将导致未定义的行为(最可能是内存损坏)。
解决方案1
如果您想继续使用C standard library file 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;
}
当然,您应该考虑的下一件事是用矢量替换经典数组(您不必提前定义它们的大小)。