简体   繁体   English

动态char字段一次读取一个char

[英]Dynamic char field reading one char at the time

#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{

char * text = new char;
scanf("%c", text);
scanf("%c", text+1);

return 0;
}    

Sorry for this lame question... I'm trying to read a string one char at a time (because I need to check sth for every char..) For input "ab" the output is "ab" and a ?random? 抱歉,这个la脚的问题……我正在尝试一次读取一个字符的字符串(因为我需要为每个字符检查sth。)对于输入“ ab”,输出为“ ab”,并且是随机字符? character... It doesn't work without the 'scanf("%c", text+1);' 字符...如果没有'scanf(“%c”,text + 1);',则无法使用 either.. I can do this using static field, but this version gives me one extra char in the end.. What am I doing wrong? 也可以..我可以使用静态字段来执行此操作,但是此版本最终给了我一个额外的字符。.我在做什么错? :'( :'(

You allocate one char giving you the pointer text . 您分配一个char给您指针text You then access text[0] and text[1] which clearly give an out of bounds access. 然后,您可以访问text[0]text[1] ,它们显然会超出范围。 I strongly recommend you don't access memory explicitly and use a std::string instead, eg: 我强烈建议您不要显式访问内存,而应使用std::string ,例如:

std::string text;
for (std::istreambuf_iterator<char> it(std::cin), end; it != end; ++it) {
    // do whatever checks you need to do
    text.push_back(*it);
}
std::cout << "read '" << text << "'\n";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM