【问题标题】:Get Line Number From Caret从插入符号获取行号
【发布时间】:2012-12-30 22:17:52
【问题描述】:

我正在尝试从文本框中的插入符号位置获取行号,这就是我所拥有的:

int Editor::GetLineFromCaret(const std::wstring &text)
{
    unsigned int lineCount = 1;

    for(unsigned int i = 0; i <= m_editWindow->SelectionStart; ++i)
    {
        if(text[i] == '\n')
        {
            ++lineCount;
        }
    }

    return lineCount;
}

但我遇到了一些奇怪的错误。例如,如果我在文本框中有 10 行文本并使用此功能,它不会给我正确的行号,除非插入符号在该行中大约 10 个字符,并且某些行没有字符,所以它是不正确的。

这就是我在 Damir Arh 的帮助下解决问题的方法:

int Editor::GetLineFromCaret(const std::wstring &text)
{
    unsigned int lineCount = 1;
    unsigned int selectionStart = m_editWindow->SelectionStart;

    for(unsigned int i = 0; i <= selectionStart; ++i)
    {
        if(text[i] == '\n')
        {
            ++lineCount;
            ++selectionStart;
        }
    }

    return lineCount;
}

【问题讨论】:

    标签: c++ windows-8 textbox microsoft-metro windows-runtime


    【解决方案1】:

    您的计算不起作用,因为新行占用字符串中的两个字符 (\r\n),但 SelectionStart 值仅将新行计为单个字符。因此,在每个新行之后,您会减少 1 个字符,即您需要将一个字符进一步移动到该行中,然后才能检测到正确的行。

    要修正计算,您需要考虑\r 个字符:

    int Editor::GetLineFromCaret(const std::wstring &text)
    {
        unsigned int lineCount = 1;
        unsigned int selectionStart = m_editWindow->SelectionStart;
    
        for(unsigned int i = 0; i <= m_editWindow->SelectionStart; ++i)
        {
            if(text[i] == '\n')
            {
                ++lineCount;
            }
            if(text[i] == '\r')
            {
                ++selectionStart;
            }
        }
    
        return lineCount;
    }
    

    【讨论】:

    • 当我回到上一行时,您的 lineCount 减少了一个。我会将您的答案标记为正确,因为您帮助我找出了问题所在。我不必考虑 '\r' 。我用答案更新了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 2015-08-26
    • 2019-07-22
    • 1970-01-01
    相关资源
    最近更新 更多