簡體   English   中英

編寫整數,浮動到文本文件

[英]Writing Ints, floats to a text file

我有個問題。 我想將Ints和Floats寫入文本文件,但是當我嘗試這樣做時,它將無法正常工作。 嘗試時,我在文本文件中得到了%d。 這是我的代碼的一部分。

void controleformules::on_pushButton_4_clicked()
{
    QString str= ui->textEdit_2->toPlainText();

    QString filename= str+".txt";

    QFile file( filename );

    if ( file.open(QIODevice::ReadWrite) )
    {

         QTextStream stream( &file );
         stream << "U heeft nu deze 2 formules gekozen:
              Formule 1: %dx + %dy = %0.1f. 
              Formule 2: %dx + %dy = %d", x1Int, y1Int, r1Int, x2Int, y2Int, r2Int;

         stream << "eerst moet je in beide formules de x of de y elimeneren, wij doen de y eerst";

     }
 }

希望您能幫我蒂姆·史密斯

C ++流無法像printf一樣使用格式字符串。 要么只使用 printf:

sprintf(buffer, "U heeft nu deze 2 formules gekozen: "
                "Formule 1: %dx + %dy = %0.1f. "
                "Formule 2: %dx + %dy = %d", 
                x1Int, y1Int, r1Int, x2Int, y2Int, r2Int);
stream << buffer;

或獨自呆在流上:

stream << "U heeft nu deze 2 formules gekozen: Formule 1: "
       << x1Int << "x + " << y1Int << "y = " << r1Int << ". Formule 2: "
       << x2Int << "x + " << y2Int << "y = " << r2Int;

浮點格式為%0.1f ,但是與之匹配的變量稱為r1Int 小心不確定的行為。

C ++中有兩種不同的文本系統。 一種是iostream,它使用插入器:

int n = 3;
std::cout << "This is a number: " << n << '\n';

另一個是printf及其親戚。 他們來自C:

int n = 3;
printf("This is a number: %d\n", n);

我不熟悉QTextStream,但這是獲得所需內容的完整格式源。

stream << ("U heeft nu deze 2 formules gekozen: Formule 1: " << x1Int << " + " << y1Int << " = " << r1Int << ". Formule 2: " << x2Int << " + " <<  y2Int << " = " r2Int);

這比較麻煩,但是它將為您提供所需的格式。

您可以混合使用流和sprintf的方式。 他們是不同的。

對於流,您無需使用%d類的占位符-您只需在要插入值的位置插入值即可。 像這樣:

stream 
  << "U heeft nu deze 2 formules gekozen: Formule 1: "
  << x1Int
  << " + " 
  << y1Int 
  << " = "
  << r1Int
  << "." 
  << y2Int
  << " Formule 2: ";

..等等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM