cout无法输出常量字符串但可输出变量的问题排查
Fixing Missing "date:"/"task:" Labels in Your Output
Let's break down what's going wrong here and fix it step by step.
The Root Cause
Your code uses getline(myFile, str, '-') to split the entire file by the '-' character, instead of first reading each task record line by line. This causes critical issues because:
- When a task ends with a newline followed by the next record's date, that newline and date get included in the next split string.
- This mixes up your date/task pairs and introduces unexpected line breaks, leading to missing labels in subsequent output.
For example, take the first two lines of your calend.txt:
15/05-checkpoint IART 18/05-checkpoint COMP
With '-' as the delimiter:
- First
getlinereads"15/05"(good) - Second
getlinereads"checkpoint IART\n18/05"(includes the newline and next date) - When you output this, the
\nforces"18/05"to print on its own line - Next split gives you
"checkpoint COMP"and"\n22/05", so you end up printingdate: checkpoint COMP(completely reversed!)
The Solution: Read Lines First, Split Second
The correct approach is to read each full line of the file first, then split that line into date and task using '-'. This keeps each record isolated and avoids mixing content between lines.
Here's the corrected code:
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myFile("calend.txt"); string line; // Read one full task record at a time while (getline(myFile, line)) { // Locate the '-' that separates date and task size_t dashPosition = line.find('-'); if (dashPosition != string::npos) { // Split the line into date (before '-') and task (after '-') string date = line.substr(0, dashPosition); string task = line.substr(dashPosition + 1); // Print with consistent labels cout << "date: " << date << endl; cout << "task: " << task << endl; } else { // Handle lines that don't follow the date-task format cout << "Warning: Invalid line format -> " << line << endl; } } myFile.close(); system("pause"); return 0; }
What This Fix Does
- Isolates records: Reading full lines ensures each date-task pair stays together, no cross-line contamination.
- Clean splitting: Using
string::findandsubstrgives precise control over where to split each line. - Error handling: Adds a warning for lines without a
'-'to avoid unexpected crashes or garbage output.
Expected Output
Running this corrected code with your calend.txt will produce the consistent, labeled output you want:
date: 15/05 task: checkpoint IART date: 18/05 task: checkpoint COMP date: 22/05 task: SDIS date: 25/05 task: apresentacao PPIN date: 27/05 task: IART date: 28/05 task: apresentacao LPOO date: 28/05 task: teste PPIN date: 01/06 task: LBAW date: 05/06 task: COMP date: 08*14/06 task: PPIN
内容的提问来源于stack exchange,提问作者NoHoly
相关产品推荐
相关产品推荐

