分享
三行代码  ›  专栏  ›  技术社区  ›  EliasDickinson

使用循环将多行写入.txt

c++
  •  2
  • EliasDickinson  · 技术社区  · 5 天前

    Martha 1 1 1 1
    Leela 2 2 2 2
    Jorge 3 3 3 3
    

    但我却得到了

    Martha 1 1 1 1Leela 2 2 2 2Jorge 3 3 3 3
    

    我的代码是:

    outFile.open("C:\\data\\agentSales.txt");
    
    for (numRealtor; numRealtor > 0; numRealtor--) {
            std::cout << "\nEnter realtor's name: ";
            std::getline(std::cin, realtorName);
            outFile << realtorName;
            for (int i = 0; i < 4; i++)
            {
                std::cout << "\nValue for house " << i + 1 << "> ";
                std::cin >> salesInput;
                if (salesInput < 0 || salesInput > 200)
                {
                    std::cout << "Error: Input must be between 0 and 200! :";
                    std::cin >> salesInput;
                }
                outFile << " " << salesInput;
    
            }
    
        }
        outFile.close();
    
    1 回复  |  直到 5 天前
        1
  •  1
  •   Grant Singleton    5 天前

    您不会在任何地方添加新行。你需要 outFile << '\n' 在第二个循环之后

    outFile.open("C:\\data\\agentSales.txt");
    
    for (numRealtor; numRealtor > 0; numRealtor--) {
            std::cout << "\nEnter realtor's name: ";
            std::getline(std::cin, realtorName);
            outFile << realtorName;
            for (int i = 0; i < 4; i++)
            {
                std::cout << "\nValue for house " << i + 1 << "> ";
                std::cin >> salesInput;
                if (salesInput < 0 || salesInput > 200)
                {
                    std::cout << "Error: Input must be between 0 and 200! :";
                    std::cin >> salesInput;
                }
                outFile << " " << salesInput;
    
            }
            outFile << '\n';
        }
        outFile.close();