【问题标题】:Read a number, then print the integers from 1 to the number to a file读取一个数字,然后将从 1 到该数字的整数打印到文件中
【发布时间】:2015-09-09 10:47:33
【问题描述】:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    [[NSFileManager defaultManager] createFileAtPath:@"E:/NumsToIntFile" contents:nil attributes:nil];

    int num = 0;
    int x = 1;

    printf("\nEnter a number: ");
    scanf("%d", &num);

    while(num >= x)
    {
       NSString *str = [NSString stringWithFormat:@"%d ", x];
       [str writeToFile:"E:/NumsToIntFile" atomically:YES encoding:NSUTF8StringEncoding error:nil];
       x++;
    }

    NSString *contents = [NSString stringWithContentsOfFile:@"E:/NumsToIntFile"];
    NSLog(@"%@",contents);
    [pool release];
    return 0;
} 

这段代码到底有什么问题?第 17 行 ([str writeToFile:"E:/NumsToIntFile" atomically:YES encoding:NSUTF8StringEncoding error:nil];) 中的内容会产生错误,我不知道如何解决。

注意:这是通过 Windows 7 上的 Notepad++ 实现的

【问题讨论】:

  • main.m: 在函数'main'中:main.m:17:5: 警告从不兼容的指针类型传递'writeToFile:atomatically:encoding:error:'的争论1 [默认启用]

标签: objective-c


【解决方案1】:

在第 17 行的 "E:/NumsToIntFile" 参数前面添加 at 符号 @

【讨论】:

  • 它可以工作,但还有一个错误:main.m:17:5: 警告:从不兼容的指针类型传递 'writeToFile:atomatically:encoding:error:' 的争论 4 [默认启用] main .m:17:5: 注意:预期的 'struct NSError **' 但争论的类型是 'id'
  • 像这样声明一个 NSError 指针:NSError *error; 并将其地址作为第四个参数传递:[str writeToFile:@"E:/NumsToIntFile" atomically:YES encoding:NSUTF8StringEncoding error:&amp;error];
  • writeToFile:... 不会附加到文件中。要追加,请使用NSFileHandle。见Appending to the end of a file with nsmutablestring
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
相关资源
最近更新 更多