如何从stringstream打印数据到文件?

我已经使用CreateFile fn打开了一个文件,并试图将数据打印到文件中。 由于数据中包含一些打印语句

wprintf(L"Channel %s was not found.\n", pwsPath);

DATA和pwsPath的声明

 #include <iostream> #include <sstream> using namespace std; string data; LPWSTR pwsPath = L"Channel1"; 

我试图使用stringstream来获取数据,并将其转换为LPCVOID以使用所示的WriteFile fn

 hFile1 = CreateFile(L"MyFile.txt", // name of the write GENERIC_WRITE, // open for writing 0, // do not share NULL, // default security CREATE_ALWAYS, // create new file only FILE_ATTRIBUTE_NORMAL, // normal file NULL); std::stringstream ss; ss << "Channel" << pwsPath << "was not found."; ss >> data; cout << data; // data contains value only till the first space ie Channel093902 cin>>data; bErrorFlag = WriteFile( hFile1, // open file handle data.c_str(), // start of data to write dwBytesToWrite, // number of bytes to write &dwBytesWritten, // number of bytes that were written NULL); 

可变数据是否可能包含stringstream中的空格? 或者除了stringstream之外,还有其他的方式来从这些打印语句中获取数据并写入文件吗?

>>操作符会将流中的下一个“单词”传递给您给定的字符串对象。 如你所发现的那样,它在第一个空白处断开。 有几种方法可以实现你想要的。 最符合的是打开输出文件作为一个流:

 #include <iostream> #include <sstream> #include <fstream> using namespace std; int main() { std::string pwsPath { "[enter path here]" }; std::stringstream ss; ss << "Channel " << pwsPath << " was not found."; std::ofstream outFile("myFile.txt"); outFile << ss.rdbuf(); outFile.close(); std::ifstream inFile("myFile.txt"); cout << inFile.rdbuf(); return 0; } 

否则你可以从ostringstream中获得内部字符串:

 std::string myData = ss.str(); size_t dataLength = myData.length(); DWORD dwBytesWritten = 0; BOOL bErrorFlag = WriteFile( hFile1, // open file handle myData.data(), // start of data to write DWORD(dataLength), // number of bytes to write &dwBytesWritten, // number of bytes that were written NULL); 

除非您有充分的理由使用CreateFile和WriteFile,否则请考虑一直使用std对象。

你的代码可能是这样的:

 #include <iostream> #include <fstream> // add this #include <sstream> // remove this unless used elsewhere // your pwsPath std::wstring path{ L"Channel1" }; std::wofstream out{ L"MyFile.txt", std::wofstream::trunc }; // skip the stringstream completely out << "Channel " << path << " was not found."