-1

有什么方法可以使用 istringstream 读取嵌入空字符的字符串?例如,如果我有一个字符数组“125 320 512 750 333\0 xyz”。有什么方法可以在空字符之后得到“xyz”?

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    std::string stringvalues = "125 320 512 750 333\0 xyz";

    cout << "val: " << stringvalues << endl;

    std::istringstream iss (stringvalues);

    for (int n=0; n<10; n++)
    {
        string val;
        iss >> val;
        std::cout << val << '\n';
    }
    
    return 0;
}

这是一个从 cplusplus.com 修改的示例。我想得到空字符之后的部分,我很好奇在不知道 char 数组的确切长度的情况下是否可以得到它。提前致谢。

4

2 回答 2

2

只需使用适当大小的 char 数组正确初始化字符串即可。其余的自然会随之而来。

#include <sstream>
#include <string>
#include <cstring>
#include <iostream>
#include <iomanip>
int main() {
    const char array[] = "125 320 512 750 333\0 xyz";

    // to get the string after the null, just add strlen
    const char *after_the_null_character = array + strlen(array) + 1;
    std::cout << "after_the_null_character:" << after_the_null_character << std::endl;

    // initialized with array and proper, actual size of the array
    std::string str{array, sizeof(array) - 1};
    std::istringstream ss{str};
    std::string word;
    while (ss >> word) {
        std::cout << "size:" << word.size() << ": " << word.c_str() << " hex:";
        for (auto&& i : word) {
            std::cout << std::hex << std::setw(2) << std::setfill('0') << (unsigned)i;
        }
        std::cout << "\n";
    }
}

会输出:

after_the_null_character: xyz
size:3: 125 hex:313235
size:3: 320 hex:333230
size:3: 512 hex:353132
size:3: 750 hex:373530
size:4: 333 hex:33333300
size:3: xyz hex:78797a

请注意读取后的零字节333

于 2020-11-22T13:06:46.350 回答
2

有什么方法可以使用 istringstream 读取嵌入空字符的字符串?

是的。您可以使用任何 UnformattedInputFunction(例如read成员函数)来读取包括空字符在内的输入。

但是请注意,您stringvalues在 null char 之后不包含任何内容,因此从它构造的字符串流也不包含任何内容。如果你想要一个std::string包含空字符(除了终止字符),那么你可以使用例如接受大小作为第二个参数的构造函数。

我想得到空字符之后的部分,我很好奇在不知道 char 数组的确切长度的情况下是否可以得到它。

这是一个简单的方法:

const char* string = "125 320 512 750 333\0 xyz";
std::size_t length = std::strlen(string);
const char* xyz = string + length + 1;
于 2020-11-22T13:08:27.903 回答